Search code examples
dartepoch

How to get a timestamp in Dart?


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?


Solution

  • 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