How to Get Difference Between Two DateTime in Dart/Flutter

In this example, we are going to show you how to get the difference between two DateTime in days, hours, minutes, and seconds in Dart/Flutter. DateTime is an important component, you may need to calculate the difference between two DateTime.

If you what to Get the difference of two dates in Weeks, Months, and Years, see this: How to get Difference of Two Dates in Weeks, Months and Years in Flutter

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-09-12 10:57:00");

Duration diff = dt1.difference(dt2);

print(diff.inDays);
//output (in days): 1198

print(diff.inHours);
//output (in hours): 28752

print(diff.inMinutes);
//output (in minutes): 1725170

print(diff.inSeconds);
//output (in seconds): 103510200

Check if the difference is negative:

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-09-12 10:57:00");

Duration diff = dt1.difference(dt2);

if(diff.isNegative){
    print("Difference is negative");
}

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {

    DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
    DateTime dt2 = DateTime.parse("2018-09-12 10:57:00");

    Duration diff = dt1.difference(dt2);

    return Scaffold(
         appBar: AppBar(
            title: Text("Calculate Difference between DateTime"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:[
         
                      Text("DT1:" + dt1.toString()),
                      Text("DT2:" + dt2.toString()),

                      Text("Difference in Days: " + diff.inDays.toString()),
                      Text("Difference in Hours: " + diff.inHours.toString()),
                      Text("Difference in Minutes: " + diff.inMinutes.toString()),
                      Text("Difference in Seconds: " + diff.inSeconds.toString()),

                ]
             ),
          )
      );
  }
}

In this way, you can calculate the difference between two DateTime in Dart/Flutter.

No any Comments on this Article


Please Wait...