Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing dates with dart

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?

like image 513
Fedy2 Avatar asked Aug 11 '14 21:08

Fedy2


People also ask

How do I change the date format in darts?

You can use the intl package (installer) to format dates. For non- en_US dates, you need to explicitly load in the locale. See the DateFormat docs for more info. The date_symbol_data_local.


2 Answers

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));
}
like image 55
Günter Zöchbauer Avatar answered Oct 02 '22 03:10

Günter Zöchbauer


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

var jiffy = Jiffy("Mon, 11 Aug 2014 12:53 pm PDT", "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();
like image 3
Jama Mohamed Avatar answered Oct 03 '22 03:10

Jama Mohamed