Search code examples
datetimeflutterdart

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

  • There is no direct way of getting that kind of date format as of now. There is a work-around.

    • Add the intl package
    • import it to your file using import 'package:intl/intl.dart';
    • Write the following code:
    var dateTime = DateTime.now();
    var val      = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(dateTime);
    var offset   = dateTime.timeZoneOffset;
    var hours    = offset.inHours > 0 ? offset.inHours : 1; // For fixing divide by 0
    
    if (!offset.isNegative) {
      val = val +
          "+" +
          offset.inHours.toString().padLeft(2, '0') +
          ":" +
          (offset.inMinutes % (hours * 60)).toString().padLeft(2, '0');
    } else {
      val = val +
          "-" +
          (-offset.inHours).toString().padLeft(2, '0') +
          ":" +
          (offset.inMinutes % (hours * 60)).toString().padLeft(2, '0');
    }
    print(val);