sdk
sdk copied to clipboard
Should be able to parse DateTime as UTC.
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 method DateTime.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.
Adding Z to the string is a reasonable solution. The parse function is intended to be the inverse of toString, and that's what toString adds for UTC times.
Adding an isUtc to parse could also work (would it then throw if the was a +02:00 time zone on the string?)
Adding
Zto the string is a reasonable solution.
No, it's not. If the time does come with the indication Z, it will be a double Z and format exception.
I wonder why the Dart team don't use industry standards like Joda / Noda Time...
The current DateTime class offers so little type-safety. It's just a little bit better than using an int.
The main reason for Dart's DateTime design is compatibility with JavaScript Date (as it was ten years ago, although I don't thinkt it has changed much since — since we haven't needed to change anything).
I may be wrong, but my feeling is that DateTime.parse(text)?.copyWith(isUtc: true) is also an option when parsed ISO 8601 is an UTC content without explicit UTC timezone declared.
It would be nice to have LocalDateTime and UTCDateTime classes that enforce it at the type level