How to add/remove a duration to/from a date in Dart

Updated: February 7, 2023 By: A Goodman Post a comment

In Dart (and Flutter), you can add or subtract a duration (days, hours, etc.) to or from a DateTime object by using the add() and subtract() methods, respectively. Here’re some real-world use cases of doing this:

  • Calculating expiration dates: You can add a duration to a DateTime object to calculate an expiration date for a product or service (especially subscription/rent services)
  • Reminding the user: You can subtract a duration from the current date to find out a date in the past when an event happened

Example

Here’s an example of adding 7 days and 10 hours to a DateTime object:

void main() {
  DateTime someDate = DateTime(2023, 2, 5, 10, 30);

  // Duration: 7 days and 10 hours
  Duration duration = const Duration(days: 7, hours: 10);

  DateTime futureDate = someDate.add(duration);

  print(futureDate);
}

Output:

2023-02-12 20:30:00.000

If you want to format the output in a human-friendly format, see this article: 4 Ways to Format DateTime in Flutter.

Another Example

Let’s say the age of a football player is 30 years old and 115 days. What we want to find out is his birth date. Here’s the code:

void main() {
  DateTime now = DateTime.now();
  Duration age = const Duration(days: 30 * 365 + 115);
  DateTime dateOfBirth = now.subtract(age);

  print("Today is: $now");
  print("Birth date is: $dateOfBirth");
}

Output:

Today is: 2023-02-08 05:04:09.834129
Birth date is: 1992-10-23 05:04:09.834129

That’s it. Further reading:

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles