Skip to content

[Flutter] DateTime in Dart Tutorial (With Example)

Last Updated on 2021-10-13 by Clay

In the Dart language, if there is a need to process time, date... etc., it can be done through the operation of DateTime class object.

DateTime class is an object that records time nodes. It can construct any time, compare the time sequence, or increase and decrease the time.

The following, I will introduce how to use DateTime.


Create DateTime object

Use DateTime.now() to create the current time

void main() {
  var now = DateTime.now();
  print(now);
}


Output:

2021-03-04 13:50:46.137


Use DateTime.utc() to create a specified time

DateTime.utc() can create the local time of the current device.

void main() {
  var datetime = DateTime.utc(2020, 12, 22, 23, 22);
  print(datetime);
}


Output:

2020-12-22 23:22:00.000Z



Addition and subtraction of DateTime objects

  • subtract(Duration duration): Subtract the time set by the Duration object
  • add(Duration duration): Increase the time set by the Duration object
  • difference(DateTime other): Returns the time difference of the Duration object

What is the difference between DateTime and Duration?

Simply put, the DateTime object is a time point, and the Duration is a time period.

We can change the time of the DateTime object via the Duration object.

Let's take a program to modify the time:

void main() {
  // ATime
  var ATime = DateTime.utc(2020, 12, 22, 23, 22);
 
  // subtract() => BTime
  var BTime = ATime.subtract(Duration(days: 2));
  
  // add() => CTime
  var CTime = BTime.add(Duration(days: 2));
  
  // Print
  print("ATime: ${ATime}");
  print("BTime: ${BTime}");
  print("CTime: ${CTime}");
}


Output:

ATime: 2020-12-22 23:22:00.000Z
BTime: 2020-12-20 23:22:00.000Z
CTime: 2020-12-22 23:22:00.000Z


As you can see, BTime is two days less than Atime, and CTime is two more days from BTime.

In addition to days, there are other types of time units that Duration can set:

  • days
  • hours
  • minutes
  • seconds
  • milliseconds
  • microsecond

Comparison of different DateTime objects

If you want to compare which "earlier" or "later" at different time points, you can use the following function to complete:

  • isAtSameMomentAs(DateTime other)
  • isAfter(DateTime other)
  • isBefore(DateTime other)
void main() {
  // ATime
  var ATime = DateTime.utc(2020, 12, 22, 23, 22);
 
  // subtract() => BTime
  var BTime = ATime.subtract(Duration(days: 2));
  
  // add() => CTime
  var CTime = BTime.add(Duration(days: 2));
  
  // Print
  print("ATime is before BTime: ${ATime.isBefore(BTime)}");
  print("ATime is after BTime: ${ATime.isAfter(BTime)}");
  print("ATime is equal to CTime: ${ATime.isAtSameMomentAs(CTime)}");


Output:

ATime is before BTime: false
ATime is after BTime: true
ATime is equal to CTime: true

References


Read More

Leave a Reply