Dart DateTime subtract()
Syntax & Examples


Syntax of DateTime.subtract()

The syntax of DateTime.subtract() method is:

 DateTime subtract(Duration duration) 

This subtract() method of DateTime returns a new DateTime instance with duration subtracted from this.

Parameters

ParameterOptional/RequiredDescription
durationrequiredthe duration to subtract from this DateTime instance

Return Type

DateTime.subtract() returns value of type DateTime.



✐ Examples

1 Subtract 2 hours and 15 minutes from a DateTime instance

In this example,

  1. We create a DateTime instance named date1 with the value '2023-05-01 10:30'.
  2. We create a Duration instance named duration representing 2 hours and 15 minutes.
  3. We then use the subtract() method to subtract duration from date1.
  4. The resulting DateTime instance is printed to standard output.

Dart Program

void main() {
  DateTime date1 = DateTime(2023, 5, 1, 10, 30);
  Duration duration = Duration(hours: 2, minutes: 15);
  DateTime newDate = date1.subtract(duration);
  print('New date after subtraction: $newDate');
}

Output

New date after subtraction: 2023-05-01 08:15:00.000

2 Subtract 1 day from a DateTime instance

In this example,

  1. We create a DateTime instance named date2 with the value '2023-05-01 12:00'.
  2. We create a Duration instance named duration representing 1 day.
  3. We then use the subtract() method to subtract duration from date2.
  4. The resulting DateTime instance is printed to standard output.

Dart Program

void main() {
  DateTime date2 = DateTime(2023, 5, 1, 12, 0);
  Duration duration = Duration(days: 1);
  DateTime newDate = date2.subtract(duration);
  print('New date after subtraction: $newDate');
}

Output

New date after subtraction: 2023-04-30 12:00:00.000

3 Subtract 30 minutes from a DateTime instance

In this example,

  1. We create a DateTime instance named date3 with the value '2023-05-01 10:30'.
  2. We create a Duration instance named duration representing 30 minutes.
  3. We then use the subtract() method to subtract duration from date3.
  4. The resulting DateTime instance is printed to standard output.

Dart Program

void main() {
  DateTime date3 = DateTime(2023, 5, 1, 10, 30);
  Duration duration = Duration(minutes: 30);
  DateTime newDate = date3.subtract(duration);
  print('New date after subtraction: $newDate');
}

Output

New date after subtraction: 2023-05-01 10:00:00.000

Summary

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