2

I want to convert string to DateTime in dart. I tried,

String timeVal = "Thu, 25 Mar 2021 19:29:28 GMT";
DateTime.parse(timeVal);

but getting an exception,

FormatException (FormatException: Invalid date format Thu, 25 Mar 2021 19:29:28 GMT)

How could I convert such a string value to DateTime in dart

Kavin-K
  • 1,948
  • 3
  • 17
  • 48
  • 1
    You'll probably need the DateFormat.parse() from the 'intl' package. – Randal Schwartz Feb 23 '21 at 20:33
  • 2
    Does this answer your question? [convert datetime string to datetime object in dart?](https://stackoverflow.com/questions/49385303/convert-datetime-string-to-datetime-object-in-dart) `HttpDate.parse` should be able to do it. – jamesdlin Feb 23 '21 at 20:54

1 Answers1

2

You can use the intl package:

import 'package:intl/intl.dart';

void main() {
  final string = 'Thu, 25 Mar 2021 19:29:28 GMT';
  final formatter = DateFormat('EEE, d MMM yyyy HH:mm:ss');
  final dateTime = formatter.parse(string);
  print(dateTime); // prints : 2021-03-25 19:29:28.000
}

For more info, see this answer and the DartFormat class docs.

Please note, the parsed DateTime in the example does not have the correct time zone (ie dateTime.timeZoneName will return your local time zone).

osaxma
  • 2,657
  • 2
  • 12
  • 21