Posted in

How to Add or Subtract Days from DateTime in Dart/Flutter

How to Add or Subtract Days from DateTime in Dart/Flutter
How to Add or Subtract Days from DateTime in Dart/Flutter

How to Add or Subtract Days from DateTime in Dart/Flutter

Manipulating dates is a fundamental task in almost any application. Whether you’re calculating an expiration date, figuring out a past event, or scheduling future notifications, you’ll inevitably need to add or subtract days from a DateTime object.

Fortunately, Dart makes this process incredibly simple and intuitive. This guide will show you the correct way to do it.

The Core Concept: Using Duration

The key to all DateTime arithmetic in Dart is the Duration class. A Duration represents a span of time. You can’t just add the number 10 to a DateTime; you must add a Duration of 10 days.

Creating a duration for a specific number of days is straightforward:

const durationOfTenDays = Duration(days: 10);
const durationOfOneWeek = Duration(days: 7);
Dart

Adding Days to a DateTime

To add time to a date, use the add() method. This method takes a Duration object and returns a new DateTime instance with the duration added.

Your original DateTime object remains unchanged.

Code Example

void main() {
  // Get the current date and time
  final now = DateTime.now();

  print('Original Date:  $now');
  // Example Output: Original Date:  2025-07-05 17:24:14.000

  // Add 15 days to the current date
  final futureDate = now.add(const Duration(days: 15));
  
  print('15 Days Later: $futureDate');
  // Example Output: 15 Days Later: 2025-07-20 17:24:14.000
}
Dart

The DateTime class automatically handles all the complex logic, like changing the month or year correctly.

Subtracting Days from a DateTime

To go back in time, use the subtract() method. It works just like add(), taking a Duration and returning a new DateTime instance in the past.

Code Example

void main() {
  // Get the current date and time
  final now = DateTime.now();

  print('Original Date:   $now');
  // Example Output: Original Date:   2025-07-05 17:24:14.000

  // Subtract 30 days from the current date
  final pastDate = now.subtract(const Duration(days: 30));

  print('30 Days Before: $pastDate');
  // Example Output: 30 Days Before: 2025-06-05 17:24:14.000
}
Dart

Key Takeaways

  • Use add() and subtract(): These are the dedicated methods for DateTime arithmetic.
  • Pass a Duration: Always specify the amount of time using a Duration object (e.g., Duration(days: 5)).
  • Immutability is Key: add() and subtract() do not change the original DateTime object. They always return a new instance, which is a safe and predictable pattern.

Anynew24.com Is A Team Of Passionate Flutter Developers On A Mission To Empower The Community. We Share Our Expertise And Insights Through Comprehensive Guides, Tutorials, And Resources, Making Flutter Mobile App Development Accessible And Enjoyable For Everyone.

Leave a Reply