parsingdatedatetimedart

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?


Solution

  • 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));
    }