flutterdartdatetimemilliseconds

Dart : Flutter - How to convert a date , which is in the form of "01 January 2020" to milliseconds since epoch?


Is there a function or a way to convert "01 January 2020" , this form of date to milliseconds since epoch?

Currently I am using this approach :

Map months = {
  "Jan": 1,
  "Feb": 2,
  "Mar": 3,
  "May": 5,
  "Jun": 6,
  "Jul": 7,
  "Aug": 8,
  "Sep": 9,
  "Oct": 10,
  "Nov": 11,
  "Dec": 12,
};

date = "01 January 2020";
var millis = DateTime(int.parse(date!.substring(date.length - 4, date.length)), months[date.substring(3,6)] ,
int.parse(date.substring(0, 2));

I don't think it is the best approach to use .


Solution

  • In order to get millisecondsSinceEpoch from a formatted date string, you need to convert the formatted string to a DateTime object.

    To achieve this, create a DateTime format that matches your date string, using the intl package. For your case, the formatter is;

    DateFormat customDateFormat = DateFormat('dd MMMM yyyy');
    

    Then parse the date string using customDateFormat, and then you'll get a DateTime object, which gives you millisecondsSinceEpoch

    DateTime dateTime = customDateFormat.parse(dateString);
    dateTime.millisecondsSinceEpoch