Ahmed Mostafa
Ahmed Mostafa

Reputation: 696

How to convert From DateTime to unix timestamp in Flutter or Dart in general

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

Answers (3)

Roger Lipscombe
Roger Lipscombe

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

PAGE BUNNII
PAGE BUNNII

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

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657676

Darts DateTime has a property millisecondsSinceEpoch which should be what unix timestamp is as well.

DateTime.now().toUtc().millisecondsSinceEpoch

Upvotes: 56

Related Questions