[英]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:您的代码中有两个问题:
offset
to int.parse instead of 'offset'
offset
传递给 int.parse 而不是'offset'
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.