How to Add and Subtract Days to Dates in Flutter

Adding and subtracting days to a specific date is not straight forward. Here, I am showing you how to add or minus days from a given date in flutter.

We have to make use of the DateTime class for this calculation purpose. We should also use methods such as add or subtract with the Duration class to get the desired results.

For example, if you want to add 30 days to today’s date then you can write it as given below.

var thirtyDaysFromNow = DateTime.now().add(new Duration(days: 30));

If you want to subtract 30 days then you can write it as given below.

var thirtyDaysMinusNow = DateTime.now().subtract(new Duration(days: 30));

Following is the complete example where I output the dates in the initial state.

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Add and Subtract Dates',
      home: DateExample(),
    );
  }
}


class DateExample extends StatefulWidget {
  DateExample({Key key}) : super(key: key);

  @override
  _DateExampleState createState() => _DateExampleState();
}

class _DateExampleState extends State<DateExample> {

@override
  void initState() {
    super.initState();
    var thirtyDaysFromNow = DateTime.now().add(new Duration(days: 30));
    var thirtyDaysMinusNow = DateTime.now().subtract(new Duration(days: 30));
    print(thirtyDaysFromNow);
    print(thirtyDaysMinusNow);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       body: Center(child: Text('Flutter Add & Subtract Days Tutorial'),),
    );
  }
}



If you want to convert the resulted dates to string then you can follow my other blog post here. I hope this tutorial will be helpful for you.

1 thought on “How to Add and Subtract Days to Dates in Flutter”

Leave a Comment

Your email address will not be published. Required fields are marked *