Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart: Convert date to yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Trying to convert DateTime.now() to this: 2019-06-04T12:08:56.235-0700

The API documentation insists that's Data format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z' but I can't figure it out for Dart. Not even python for that matter.

I've tried now.toIso8601String() but it doesn't quite nail it (i.e. 2019-12-03T17:50:23.476164). It's missing the last - section and one digit. The API call within flutter returns a {code:415 message HTTP 415 Unsupported Media Type} as a result.

What am I missing?

like image 539
Graciela Carrillo Avatar asked Oct 16 '25 03:10

Graciela Carrillo


1 Answers

Like @hata pointed out, it's not yet implemented. So, to add the Z (timezone as number) exactly as requested I did this:

String formatISOTime(DateTime date) {
    //converts date into the following format:
// or 2019-06-04T12:08:56.235-0700
    var duration = date.timeZoneOffset;
    if (duration.isNegative)
      return (DateFormat("yyyy-MM-ddTHH:mm:ss.mmm").format(date) +
          "-${duration.inHours.toString().padLeft(2, '0')}${(duration.inMinutes - (duration.inHours * 60)).toString().padLeft(2, '0')}");
    else
      return (DateFormat("yyyy-MM-ddTHH:mm:ss.mmm").format(date) +
          "+${duration.inHours.toString().padLeft(2, '0')}${(duration.inMinutes - (duration.inHours * 60)).toString().padLeft(2, '0')}");
  }

Implemented:

  void main() {
    DateTime getCurrentTimestamp = DateTime.now();
    print('agreement signed');
    String agreementSigned = formatISOTime(getCurrentTimestamp);
    print(agreementSigned);
  }

When ran:

main();

// Result:

2021-10-29T17:53:56.053+0100

like image 174
Graciela Carrillo Avatar answered Oct 18 '25 21:10

Graciela Carrillo



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!