How to get a timestamp in Dart?
DartEpochDart 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).