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 .
CodePudding user response:
Did it using this approach :
var value1 = "01 January 2020";
var dateTimeFormat_v1 =DateFormat('dd MMMM yyyy', 'en_US') .parse(value1.toString());
print(dateTimeFormat_v1.millisecondsSinceEpoch);
CodePudding user response:
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
CodePudding user response:
This was somewhat tricky but I managed to make it work, this is a pretty straightforward approach to get your answer:
void main() {
String date = "1 January 2022";
print(convert(date));
}
int convert(String date){
List<String> a = [];
a = date.split(" ");
List month = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
String converted = "${a[2]}-${(month.indexOf(a[1]) 1).toString().length==1 ? "0${month.indexOf(a[1]) 1}" : "${month.indexOf(a[1]) 1}"}-${a[0].length==1?"0${a[0]}": "${a[0]}"}";
DateTime a2 = DateTime.parse(converted);
print(converted);
return a2.microsecondsSinceEpoch;
}