'How do I format DateTime with UTC timezone offset?

What type of date format is this?

2020-03-26T00:57:08.000+08:00

I'm using DateFormat class

 DateTime dateTime = DateTime.now();

 print(dateTime.toIso8601String());
 print(dateTime.toLocal());
 print(dateTime.toUtc());

Output

I/flutter (20667): 2020-03-26T01:34:20.826589
I/flutter (20667): 2020-03-26 01:34:20.826589
I/flutter (20667): 2020-03-25 17:34:20.826589Z

I would like to have a date format like the first output I show, which has the +08:00 behind. Which should I use?



Solution 1:[1]

What type of date format is this?

This format is UTC + timezone offset.

That +08:00 is the time zone's offset that has already been added.

Seems like DateTime doesn't contain timezone information, so, you can't create a DateTime in a specific timezone. Only the timezone of your system and UTC are available.

Is important to say also that DateTime support timezone offset for parsing, but normalizes it to UTC or local time.

So since this is UTC you can probably format it using toUtc or toLocal and the receiver will be able to parse it.

With that said, you can simply parse it like this:

DateTime.parse("2020-03-26T00:57:08.000+08:00")

Solution 2:[2]


What date format is this?
"2020-03-26T00:57:08.000+08:00"

This date-time format follows the RFC 3339 standard, and more generally the ISO 8601 standard. The letter "T" is known as the time designator. The "+08:00" is known as the UTC timezone offset.


I would like to have a date format [...], which has the +08:00 behind

You can add the timezone offset to the formatted date:

// import 'package:intl/intl.dart' as intl show DateFormat;

void main() {
  DateTime now = DateTime.now();

  String dateTime =
    // intl.DateFormat("yyyy-MM-dd'T'HH:mm:ss").format(now) +
    // or...
    now.toIso8601String() +
    now.timeZoneOffset.inHours.toString() + ":00"
  ;

  print(dateTime);
}

I'm using DateFormat class

DateFormat (https://api.flutter.dev/flutter/intl/DateFormat-class.html) does not format a UTC timezone offset. And while the letter "Z" in the documentation appears to provide the UTC timezone offset, it's reserved, and you can not use DateFormat("Z") as that throws an Unimplemented Error (https://api.flutter.dev/flutter/dart-core/UnimplementedError-class.html). Note that "Z" (pronounced phonetically as "zulu") stands for zero meridian time, and has a UTC timezone offset of +0:00.


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2