Dart – Dates and Times

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

filter_none

edit
close

play_arrow

link
brightness_4
code

void main(){
    
// Get the current date and time.
var now = DateTime.now();
print(now);
  
// Create a new DateTime with the local time zone.
var y2k = DateTime(2000); // January 1, 2000
print(y2k);
  
// Specify the month and day.
y2k = DateTime(2000, 1, 2); // January 2, 2000
print(y2k);
    
// Specify the date as a UTC time.
y2k = DateTime.utc(2000); // 1/1/2000, UTC
print(y2k);
    
// Specify a date and time in ms since the Unix epoch.
y2k = DateTime.fromMillisecondsSinceEpoch(946684800000,
    isUtc: true);
print(y2k);
  
// Parse an ISO 8601 date.
y2k = DateTime.parse('2000-01-01T00:00:00Z');
print(y2k);
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

void main(){
    
// 1/1/2000, UTC
var y2k = DateTime.utc(2000);
print(y2k.millisecondsSinceEpoch == 946684800000);
  
// 1/1/1970, UTC
var unixEpoch = DateTime.utc(1970);
print(unixEpoch.millisecondsSinceEpoch == 0);
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

void main(){
    
  
  
var y2k = DateTime.utc(2000);
  
// Add one year.
var y2001 = y2k.add(Duration(days: 366));
print(y2001.year == 2001);
  
// Subtract 30 days.
var december2000 = y2001.subtract(Duration(days: 30));
assert(december2000.year == 2000);
print(december2000.month == 12);
  
// Calculate the difference between two dates.
// Returns a Duration object.
var duration = y2001.difference(y2k);
print(duration.inDays == 366); // y2k was a leap year.
  
}

chevron_right


Output:

true
true
true



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.