Reputation: 696
as you seen in the title i want to convert from DateTime to unix Timestamp in Flutter (Dart Lang).
i saw the static Method that can convert from unix timestamp to DateTime :
DateTime.fromMillisecondsSinceEpoch(unixstamp);
i need the reverse
datatime => unixstamp
Thanks in advance.
Upvotes: 22
Views: 26230
Reputation: 91875
DateTime
provides millisecondsSinceEpoch
and microsecondsSinceEpoch
properties. For example:
var unixTimeMilliseconds = DateTime.now().toUtc().millisecondsSinceEpoch;
For whatever reason, there's no secondsSinceEpoch
. Since traditional Unix timestamps are in seconds, you might also want this:
extension SecondsSinceEpoch on DateTime {
int get secondsSinceEpoch => millisecondsSinceEpoch ~/ 1000;
}
Note the ~/
for integer division.
Upvotes: 3
Reputation: 358
String time = DateTime.now().millisecondsSinceEpoch.toString().substring(0, 10);
Mohamed ElSaraff answered this here: https://stackoverflow.com/a/72646505/12592516
I use this for Stripe API
Upvotes: -1
Reputation: 657676
Darts DateTime
has a property millisecondsSinceEpoch
which should be what unix timestamp is as well.
DateTime.now().toUtc().millisecondsSinceEpoch
Upvotes: 56