Date format in Dart which includes GMT

10k views Asked by At

How do I convert my current time into GMT/ UTC time in Dart, similar to the javascript way: new Date().toUTCString():

Tue, 01 Nov 2011 19:06:35 GMT

I tried couple of formatters see below but it did not work

//var f = DateFormat('E, d MMM yyyy HH:mm:ss z');
var f = DateFormat('E, d MMM yyyy HH:mm:ss'); 
    var date = f.format(DateTime.now());

4

There are 4 answers

5
Ben Butterworth On BEST ANSWER

Convert your current time to UTC and append " GMT" to the string.

import 'package:intl/intl.dart';

void main(List<String> arguments) async {
  var f = DateFormat('E, d MMM yyyy HH:mm:ss');
  var date = f.format(DateTime.now().toUtc()) + " GMT";
  print(date);
}


Using an arbitrary timezone (not just GMT/ UTC)

Although it is in the documentation, you can't create strings with arbitrary timezones with DateTime, as timezone support/ implementation has been missing, and is a GitHub issue since 2015. For example, you can't display a different timezone in the string, as using z in the format string doesn't work: callers get an UnimplementedError. See the 3 related GitHub issues: one, two and three.

UnimplementedError
#0      _DateFormatPatternField.formatTimeZone (package:intl/src/intl/date_format_field.dart:640:5)
#1      _DateFormatPatternField.formatField (package:intl/src/intl/date_format_field.dart:381:16)
#2      _DateFormatPatternField.format (package:intl/src/intl/date_format_field.dart:244:12)
#3      DateFormat.format (package:intl/src/intl/date_format.dart:276:26)
#4      main (file:///Users/benbutterworth/datetime/bin/datetime.dart:11:16)
<asynchronous suspension>
#5      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:299:32)
#6      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
2
Anuranjan Srivastav On

Finally I found out the work around as below

 String getUTCDate() {
    try {
      var f = DateFormat('E, d MMM yyyy HH:mm:ss');
      var now = DateTime.now().toUtc();
      return f.format(now) + ' GMT';
    } catch (e) {
      print('Error ******' + e.toString());
      throw e;
    }
  }
6
savke On
var f = DateFormat('EEE, d MMM yyyy HH:mm:ss'); 
var date = f.format(DateTime.now());

This output date in format Tue, 01 Nov 2011 19:06:35, without GMT

0
ahmdt On

For parsing use this:

final rfc7231DateFormat = "E, d MMM y H:m:s 'GMT'";
final myDate = DateFormat(rfc7231DateFormat).parseUTC(rawValue);