21

I need to parse this kind of date "Mon, 11 Aug 2014 12:53 pm PDT" in a DateTime object in Dart.

The DateTime has a static method parse that accepts a subset of ISO 8601 format, not my case.

The DateFormat class lets you define the date pattern to parse. I've created the pattern "EEE, dd MMM yyyy hh:mm a zzz".

Using it I get a FormatException: Trying to read a from Mon, 11 Aug 2014 12:53 pm PDT at position 23.

Looks like the parser does not like the PM marker case (I've open an issue about).

I've tried to workaround the issue upper casing the entire string. With the string all upper case I get again a FormatException due to the week day and the month names in upper case.

Any other solution or workaround?

Fedy2
  • 3,147
  • 4
  • 26
  • 44

2 Answers2

34

You can just replace the lowercase 'am'/'pm' characters by uppercase.

import 'package:intl/intl.dart';

void main() {
  var date = 'Mon, 11 Aug 2014 12:53 pm PDT';
  DateFormat format = new DateFormat("EEE, dd MMM yyyy hh:mm a zzz");
  date = date.replaceFirst(' pm', ' PM').replaceFirst(' am', ' AM');
  print(date);
  print(format.parse(date));
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
4

Try this package, Jiffy. It handles all of the parsing, no need to upper case your string

var jiffy = Jiffy.parse("Mon, 11 Aug 2014 12:53 pm PDT", pattern: "EEE, dd MMM yyyy hh:mm a zzz");

You can also format it and manipulate dateTime easily. Example

jiffy.format("dd MM yyyy");
// Or use DateFormat's default date time formats
jiffy.yMMMM;
// Also get relative time
jiffy.fromNow();
Jama Mohamed
  • 3,057
  • 4
  • 29
  • 43