Dart DateTime difference()
Syntax & Examples


Syntax of DateTime.difference()

The syntax of DateTime.difference() method is:

 Duration difference(DateTime other) 

This difference() method of DateTime returns a Duration with the difference when subtracting other from this DateTime.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe DateTime instance to subtract from this DateTime

Return Type

DateTime.difference() returns value of type Duration.



✐ Examples

1 Calculate difference between 2023-05-01 and 2023-04-01

In this example,

  1. We create two DateTime instances, date1 and date2, representing May 1, 2023, and April 1, 2023, respectively.
  2. We then calculate the difference between date1 and date2 using the difference() method.
  3. The result is a Duration representing the difference in time.
  4. We print the difference to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 1);
  DateTime date2 = DateTime(2023, 4, 1);
  Duration difference = date1.difference(date2);
  print('Difference between date1 and date2: $difference');
}

Output

Difference between date1 and date2: 720:00:00.000000

2 Calculate difference between 2023-05-01 and 2023-05-01

In this example,

  1. We create two DateTime instances, date1 and date2, representing May 1, 2023, and May 1, 2023, respectively.
  2. We then calculate the difference between date1 and date2 using the difference() method.
  3. The result is a Duration representing zero difference in time.
  4. We print the difference to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 1);
  DateTime date2 = DateTime(2023, 5, 1);
  Duration difference = date1.difference(date2);
  print('Difference between date1 and date2: $difference');
}

Output

Difference between date1 and date2: 0:00:00.000000

3 Calculate difference between 2023-05-01 and 2023-06-01

In this example,

  1. We create two DateTime instances, date1 and date2, representing May 1, 2023, and June 1, 2023, respectively.
  2. We then calculate the difference between date1 and date2 using the difference() method.
  3. The result is a Duration representing the difference in time.
  4. We print the difference to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 1);
  DateTime date2 = DateTime(2023, 6, 1);
  Duration difference = date1.difference(date2);
  print('Difference between date1 and date2: $difference');
}

Output

Difference between date1 and date2: -744:00:00.000000

Summary

In this Dart tutorial, we learned about difference() method of DateTime: the syntax and few working examples with output and detailed explanation for each example.