Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Dart – Date and Time

  • Last Updated : 23 Feb, 2021

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(){
    
// 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);
}

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(){
    
// 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);
}

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);
  
// 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.
  
}

Output:

true
true
true



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!