Reputation: 439
I am getting date from a server as a unix timestamp
, how can I convert it to ISO 8601
date format in flutter?
the date I receive:
1611694800000
How I want to convert it to be
2021-01-26T22:00:00.000+00:00
What I have done so far with no luck
String s = '1611694800000';
debugPrint("Recevied date is: $s");
String dateS = DateTime.parse(s).toIso8601String();
debugPrint("Converted date : $dateS");
String dateStr = (dateS.split(".")[0].split("T")[0] + " 00:00:00").substring(1);
debugPrint("Activation date: $dateStr");
I end up getting:
Unhandled Exception: FormatException: Invalid date format.
Upvotes: 1
Views: 2391
Reputation: 90065
Use DateTime.fromMillisecondsSinceEpoch
:
var timestampMilliseconds = 1611694800000;
var datetime =
DateTime.fromMillisecondsSinceEpoch(timestampMilliseconds, isUtc: true);
print(datetime.toIso8601String()); // Prints: 2021-01-26T21:00:00.000Z
(Note that the printed time is one hour off of your stated expectation, but I'm assuming that's a mistake in your expectation.)
Upvotes: 3
Reputation: 980
The reason why you are getting invalid date format is because you have to provide date in string like '2021-04-19' and not milliseconds;
This package makes it easy to format dates time_formatter
Upvotes: 0