Dart DateTime add()
Syntax & Examples


Syntax of DateTime.add()

The syntax of DateTime.add() method is:

 DateTime add(Duration duration) 

This add() method of DateTime returns a new DateTime instance with duration added to this.

Parameters

ParameterOptional/RequiredDescription
durationrequiredthe duration to add to this DateTime instance

Return Type

DateTime.add() returns value of type DateTime.



✐ Examples

1 Add 5 days to current date

In this example,

  1. We get the current date and time using DateTime.now().
  2. We then use the add() method with a Duration of 5 days to get the future date.
  3. We print the future date to standard output.

Dart Program

void main() {
  var now = DateTime.now();
  var future = now.add(Duration(days: 5));
  print('Future date: $future');
}

Output

Future date: 2024-05-08 15:12:49.703

2 Add 3 hours to a specific date

In this example,

  1. We create a specific date and time using DateTime(2023, 5, 10).
  2. We use the add() method with a Duration of 3 hours to calculate the end time.
  3. We print the end time to standard output.

Dart Program

void main() {
  var start = DateTime(2023, 5, 10);
  var end = start.add(Duration(hours: 3));
  print('End time: $end');
}

Output

End time: 2023-05-10 03:00:00.000

3 Add 30 minutes to a parsed date

In this example,

  1. We parse a date string using DateTime.parse() to get a DateTime instance.
  2. We add a Duration of 30 minutes using the add() method to get the new date and time.
  3. We print the new date and time to standard output.

Dart Program

void main() {
  var date = DateTime.parse('2024-12-25T08:00:00');
  var newDate = date.add(Duration(minutes: 30));
  print('New date: $newDate');
}

Output

New date: 2024-12-25 08:30:00.000

Summary

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