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

Time:10-30

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?

CodePudding user response:

It seems, as for intl/intl.dart DateFormat class, time zone has not been implemented yet.

The following characters are reserved and currently are unimplemented:

Symbol Meaning Presentation Example
z time zone (Text) Pacific Standard Time
Z time zone (RFC 822) (Number) -0800
v time zone (generic) (Text) Pacific Time

CodePudding user response:

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

  • Related