How to get a timestamp in Dart?

DartEpoch

Dart Problem Overview


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?

Dart Solutions


Solution 1 - Dart

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

Solution 2 - Dart

This is my solution

DateTime _now = DateTime.now();
print('timestamp: ${_now.hour}:${_now.minute}:${_now.second}.${_now.millisecond}');

Solution 3 - Dart

Microseconds is also available natively from Dart: (no need to import packages).

void main() {
  print(new DateTime.now().microsecondsSinceEpoch);
}

output:

> 1591457696860000

Solution 4 - Dart

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

Solution 5 - Dart

In order to get the timestamp in milliseconds from DateTime. Just use the millisecondsSinceEpoch property. Remember that this isn't a callable function rather a property.

DateTime time = DateTime.now();
time.millisecondsSinceEpoch;

January 1st, 1970 at 00:00:00 UTC is referred to as the Unix epoch. So, you'll get a number which corresponds to the milliseconds passed since Epoch. There is also a microsecondsSinceEpoch property.

Dart Documentation - https://api.dart.dev/stable/2.17.0/dart-core/DateTime/millisecondsSinceEpoch.html

Solution 6 - Dart

You can simply print the current timestamp in your timezone as a string like so:

print(DateTime.now().toString());

DateTime.Now() also has other methods like .day, .hour, .minute, etc. .millisecondsSinceEpoch is one way to get it independent of timezone - this is how many milliseconds have passed since the "Unix epoch" 1970-01-01T00:00:00Z (UTC).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1781056View Question on Stackoverflow
Solution 1 - DartKai SellgrenView Answer on Stackoverflow
Solution 2 - DartMohsen EmamiView Answer on Stackoverflow
Solution 3 - DartArthur ZennigView Answer on Stackoverflow
Solution 4 - DartRajni GujaratiView Answer on Stackoverflow
Solution 5 - DartAA ShakilView Answer on Stackoverflow
Solution 6 - DartNaveen KatragaddaView Answer on Stackoverflow