How to Find Difference Between Two Dates in Flutter

In this blog post, I am showing how to find difference between two dates in flutter. We have to make use of the DateTime class and its difference method for this purpose.

We can define two dates using DateTime class as given below.

var start = new DateTime(2020, DateTime.june, 6);
var end = new DateTime(2020, DateTime.december, 10);

Now, you can get the difference using difference method as well as the Duration class.

Duration difference = end.difference(start);

Following is the complete example where I output the the difference of two days.

import 'package:flutter/material.dart';

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Date Difference Example',
      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 start = new DateTime(2020, DateTime.june, 6);
    var end = new DateTime(2020, DateTime.december, 10);
    Duration difference = end.difference(start);
    print(difference.inDays);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       body: Center(child: Text('Flutter Date Difference Tutorial'),),
    );
  }
}



Sometimes, the date duration calculations can get messy. It’s always better to do some research before implementing it.

Leave a Comment

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