android 为什么我不能在datetime Flutter项目中添加偏移小时?

nhaq1z21  于 2023-04-04  发布在  Android
关注(0)|答案(3)|浏览(157)

我现在尝试向datetime对象添加偏移时间,但它不显示实际时间。这是我在android studio中的flutter项目。

void getTime() async {
    Response response = await
    get('http://worldtimeapi.org/api/timezone/Asia/Karachi');
    Map data = jsonDecode(response.body);
    String datetime = data['datetime'];
    String offset = data['utc_offset'].substring(1,3);

    print(offset);
    DateTime now = DateTime.parse(datetime);
    now.add(Duration(hours: int.parse('offset')));
    print(now);
    }
    @override
    void initState() {
    super.initState();
    getTime();
    }

这是我得到的结果:Screenshot of the output

kxeu7u2r

kxeu7u2r1#

你的代码中有两个问题:
1.您应该将offset传递给int.parse而不是'offset'

  1. add是对DateTime对象的不可变操作。它不会更改DataTime对象,但会返回一个新对象。
    试试这个:
DateTime dateTimeAfterOffset = DateTime.parse(datetime).add(
  Duration(
    hours: int.parse(offset),
  ),
);
pprl5pva

pprl5pva2#

我找到解决办法了耶!

void getTime() async {

    //Make the request
    Response response = await get('http://worldtimeapi.org/api/timezone/Asia/Karachi');
    Map data = jsonDecode(response.body);
    print(data);

    //Get properties from data
    String datetime = data['datetime'];
    String offset = data['utc_offset'].substring(1,3);
    //print(datetime);
    print(offset);

    //create DateTime Object
    DateTime now = DateTime.parse(datetime);
    now = now.add(Duration(hours: int.parse(offset)));
    print(now);
  }

  @override
  void initState() {

    super.initState();
    getTime();
  }
92dk7w1h

92dk7w1h3#

但将帮助您与任何类型的偏移这里是示例代码如下

void getTime() async {
    var httpsUri = Uri(
        scheme: 'http',
        host: 'worldtimeapi.org',
        path: '/api/timezone/Asia/Kolkata');

    Response response = await get(httpsUri);
    Map data = jsonDecode(response.body);
    //print('data is ${response.body}');
    //get properties from data
    String dateTime = data['datetime'];
    String offset = data['utc_offset'];
    offset = offset.replaceAll("+", "");

    /// String offset1 = data['utc_offset'].substring(1, 3);
    print('date=>$dateTime,offset=>$offset');

    //date time object
    DateTime now = DateTime.parse(dateTime);
    print('Final date before:$now');
    now = now.add(Duration(
        hours: int.parse(offset.split(':')[0]),
        minutes: int.parse(offset.split(':')[1])));
    print('Final date after:$now');
}

相关问题