Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add serializer in dart to convert iso 8601 to datetime object?

In dart I want to do this:

var s = "2018-11-23T04:25:41.9241411Z";  // string comes from a json but represented here for simplicity like this
var d = DateTime.parse(s);

but it throws a null.

Dart can't seem to parse iso 8601 date time formats. I've found a custom serializer called "Iso8601DateTimeSerializer" but how do I add it to my flutter app?

links: https://reviewable.io/reviews/google/built_value.dart/429#-

The instructions here only indicate adding it to dart using "SerializersBuilder.add" but I'm a newbie and cant find out how?

link: https://pub.dartlang.org/documentation/built_value/latest/iso_8601_date_time_serializer/Iso8601DateTimeSerializer-class.html

like image 292
fractal Avatar asked Nov 23 '18 04:11

fractal


1 Answers

The problem is that Dart's DateTime.parse only accepts up to six digits of fractional seconds, and your input has seven.

... and then optionally a '.' followed by a one-to-six digit second fraction.

You can sanitize your input down to six digits using something like:

String restrictFractionalSeconds(String dateTime) =>
    dateTime.replaceFirstMapped(RegExp(r"(\.\d{6})\d+"), (m) => m[1]);

Maybe the parse function should just accept more digits, even if they don't affect the value.

like image 139
lrn Avatar answered Oct 31 '22 23:10

lrn