DateTime.parse() tries to automatically determine whether a date string is in UTC or local time.
However, many API's don't specify timezones at all and let the client handle this.
The problem is that when no timezone offset is given, it defaults to local instead of UTC.
There is then no way to convert the DateTime to local time as it believes that it already is in local time.
Ideally, there would be a second methodDateTime.parseUtc() or DateTime.parse() would take a parameter isUtc similar to DateTime.fromMillisecondsSinceEpoch(). This would always return a UTC DateTime and ignore the timezone offset (or lack of timezone offset) specified.
+1
my API returns "2019-08-25 13:38:16"
so parsing it like
var updatedAt = DateTime.parse(data['updated_at']);
return the time in local time not UTC as what API uses
As a temp fix i did the following
createdAt = DateTime.parse("${data['created_at']}Z");
appended Z that means UTC after date
You can call
DateTime.parse(data['created_at']).toLocal() or DateTime.parse(data['created_at']).toUtc()
You can call
DateTime.parse(data['created_at']).toLocal()orDateTime.parse(data['created_at']).toUtc()
This does not work as toLocal will do nothing to a DateTime that is already in local time.
The issue is letting dart know that the DateTime is actually in UTC so that toLocal will work.
Thanks, @Saifallak, you saved me a bunch of time figuring out why my tests running on GitHub's CI servers were failing, but working fine locally. It was because of the time zone difference. The only fix I could find is to add 'Z' at the end of the date string so it gets parsed as a UTC time.
Most helpful comment
As a temp fix i did the following
appended Z that means UTC after date