How to Get Difference Between Two DateTime in Dart/Flutter
Restored from an archived snapshot captured 2021-11-28. Examples may refer to earlier Flutter versions.
In this example, we are going to show you how to get the difference between two DateTime in days, hours, minutes, seconds in Dart/Flutter. DateTime is an important component, you may need to calculate the difference between two DateTime.
How to Calculate Difference Between Two DateTime in Dart/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");
}
Flutter/Dart Example:
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()),
]
),
)
);
}
}
Output Screenshot:

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