21

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.

3 Answers 3

56

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

DateTime.now().toUtc().millisecondsSinceEpoch
2
  • 29
    Unix timestamps are in seconds, so you'll need to divide that by 1000.
    – f0xik
    Aug 31, 2019 at 17:46
  • ^ this should be the correct answer!
    – anthares
    Mar 6, 2022 at 17:40
2

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.

-1
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.