How to add serializer in dart to convert iso 8601 to datetime object?
Solution 1
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.
Solution 2
You need to add it to the serializers builder.
Example:
@SerializersFor(models)
final Serializers serializers = (_$serializers.toBuilder()
..addPlugin(StandardJsonPlugin())
..add(Iso8601DateTimeSerializer()))
.build();
Solution 3
Just to add to Irn's answer. You need to add some escapes for the regex to work properly.
String restrictFractionalSeconds(String dateTime) =>
dateTime.replaceFirstMapped(RegExp("(\\.\\d{6})\\d+"), (m) => m[1]);
fractal
Updated on December 07, 2022Comments
-
fractal over 1 year
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?