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

3

7

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

Golding answered 23/11, 2018 at 4:50 Comment(0)
L
5

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.

Lachesis answered 23/11, 2018 at 6:53 Comment(0)
T
1

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]);
Tidwell answered 30/11, 2018 at 17:1 Comment(0)
E
1

You need to add it to the serializers builder.

Example:

@SerializersFor(models)
final Serializers serializers = (_$serializers.toBuilder()
      ..addPlugin(StandardJsonPlugin())
      ..add(Iso8601DateTimeSerializer()))
    .build();
Electronic answered 10/6, 2020 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.