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
Parameter | Optional/Required | Description |
---|---|---|
duration | required | the 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,
- We get the current date and time using
DateTime.now()
. - We then use the
add()
method with aDuration
of 5 days to get the future date. - 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,
- We create a specific date and time using
DateTime(2023, 5, 10)
. - We use the
add()
method with aDuration
of 3 hours to calculate the end time. - 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,
- We parse a date string using
DateTime.parse()
to get aDateTime
instance. - We add a
Duration
of 30 minutes using theadd()
method to get the new date and time. - 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.