Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON date in Flutter

An API response I should use in my Flutter app contains date in JSON in a format like this: /Date(1559985189000+0300)/

When parsing I have the following exception: FormatException (FormatException: Invalid date format /Date(1559985189000+0300)/)

I use this code to parse: date: DateTime.parse(json["Date"])

Date string seems an unix timestamp to me.

Is there a built in way to parse this date string to DateTime in Flutter, or should I implement it?

Thanks a lot!

like image 641
Tom Avatar asked Oct 28 '25 05:10

Tom


1 Answers

You have to implement it; and you will have to experiment a bit as you haven't said what your server actually supplies. Also of note is that Dart's date only supports two timezones: UTC or local time. (The timezone package provides the whole Olsen database for manipulation of other timezones.)

Guessing from the number in the question and when you asked it, let's assume that the date is in UTC, but the server is in UTC+3 (e.g. Athens, Greece).

Start by parsing out the relevant bits:

  var raw = '/Date(1559985189000+0300)/';

  var numeric = raw.split('(')[1].split(')')[0];
  var negative = numeric.contains('-');
  var parts = numeric.split(negative ? '-' : '+');
  var millis = int.parse(parts[0]);

This will get you a DateTime in the TZ of the phone:

  var local = DateTime.fromMillisecondsSinceEpoch(millis);

This will get you the UTC time:

  var utc = DateTime.fromMillisecondsSinceEpoch(millis, isUtc: true);

This will get you the offset between Athens and UTC, but is probably useless: (note that even though we can infer that your server is in Athens (or a similar TZ), we cannot get a date in Athens timezone without using the timezone package - Dart just supports UTC or the phone's time, which might be in Zurich)

  final multiplier = negative ? -1 : 1;
  var offset = Duration(
    hours: int.parse(parts[1].substring(0, 2)) * multiplier,
    minutes: int.parse(parts[1].substring(2)) * multiplier,
  );
like image 135
Richard Heap Avatar answered Oct 29 '25 19:10

Richard Heap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!