How to get a timestamp in Dart?

user1781056 picture user1781056 · Oct 28, 2012 · Viewed 58.6k times · Source

I've been learning Dart, but I don't know how to generate a timestamp. I have tried this:

void main() {
  print((new Date()).millisecondsSinceEpoch);
}

Thanks to the IDE I was able to get this far, but I'm getting a confusing error:

Exception: No such method: 'Date'

Help?

Answer

Kai Sellgren picture Kai Sellgren · Oct 28, 2012

You almost had it right. You just did not use a named constructor:

void main() {
  print(DateTime.now().millisecondsSinceEpoch);
}

Gives:

1351441456747

See the API documentation for more: https://api.dart.dev/stable/2.10.1/dart-core/DateTime-class.html