简体   繁体   English

为什么我不能在日期时间 Flutter 项目中添加偏移时间?

[英]Why can't I add offset hours in datetime Flutter project?

I tried to add offset hours to my datetime object now, but it doesn't show the added time that is actual time.我现在尝试在我的日期时间 object 中添加偏移时间,但它没有显示实际时间的添加时间。 It is my flutter project in android studio.这是我在 android 工作室的 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();
    }

This is the result I got: Screenshot of the output这是我得到的结果: output 的截图

You have two problems in your code:您的代码中有两个问题:

  1. You should pass offset to int.parse instead of 'offset'您应该将offset传递给 int.parse 而不是'offset'
  2. add is an immutable operation on a DateTime object. add是对DateTime object 的不可变操作。 It does not change the DataTime object but returns a new one.它不会更改DataTime ,而是返回一个新的。

Try this instead:试试这个:

DateTime dateTimeAfterOffset = DateTime.parse(datetime).add(
  Duration(
    hours: int.parse(offset),
  ),
);
```

I found the solution.我找到了解决方案。 Yayyy!耶耶!

  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();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM