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

6,504

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]);
Share:
6,504
fractal
Author by

fractal

Updated on December 07, 2022

Comments