A DateTime object is a point in time. The time zone is either UTC or the local time zone. Accurate date-time handling is required in almost every data context. Dart has the marvelous built-in classes DateTime and Duration in dart:core.Some of its uses are:
- Compare and calculate with date times
- Get every part of a date-time
- Work with different time zones
- Measure time spans
Example:
Dart
void main(){
var now = DateTime.now();
print(now);
var y2k = DateTime(2000);
print(y2k);
y2k = DateTime(2000, 1, 2);
print(y2k);
y2k = DateTime.utc(2000);
print(y2k);
y2k = DateTime.fromMillisecondsSinceEpoch(946684800000,
isUtc: true );
print(y2k);
y2k = DateTime.parse( '2000-01-01T00:00:00Z' );
print(y2k);
}
|
Output:
2020-08-25 11:58:56.257
2000-01-01 00:00:00.000
2000-01-02 00:00:00.000
2000-01-01 00:00:00.000Z
2000-01-01 00:00:00.000Z
2000-01-01 00:00:00.000Z
The millisecondsSinceEpoch property of a date returns the number of milliseconds since the “Unix epoch”—January 1, 1970, UTC.
Example:
Dart
void main(){
var y2k = DateTime.utc(2000);
print(y2k.millisecondsSinceEpoch == 946684800000);
var unixEpoch = DateTime.utc(1970);
print(unixEpoch.millisecondsSinceEpoch == 0);
}
|
Output:
true
true
The Duration class can be used to calculate the difference between two dates and to move date forward or backward.
Example:
Dart
void main(){
var y2k = DateTime.utc(2000);
var y2001 = y2k.add(Duration(days: 366));
print(y2001.year == 2001);
var december2000 = y2001.subtract(Duration(days: 30));
assert (december2000.year == 2000);
print(december2000.month == 12);
var duration = y2001.difference(y2k);
print(duration.inDays == 366);
}
|
Output:
true
true
true
Last Updated :
23 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...