get difference between two data in flutter
get difference between two data in flutter

Hi Guys, Welcome to Proto Coders Point. In this Flutter/Dart article, will learn how to get time difference between dates, This is very useful when you are building any flutter application & want to substract two dates and get difference between two datetimes in flutter.

To Achieve this we will make use of DateTime.difference method of dart


void main(){
    final DateTime date1 = DateTime(2022,5,30,11,30,40);

    final DateTime date2= DateTime(2022,5,30,14,30,40);

    final Duration durdef = date2.difference(date1);

    print("${durdef.inHours} Hours");    
    //output (Time difference in Hours): 3 Hours

    print("${durdef.inDays} Days");
    //output (Time difference in days): 0

    print("${durdef.inMinutes} Minutes");
    //output (Time difference in minutes): 180

    print("${durdef.inSeconds} Seconds");
    //output (Time difference in Seconds): 10800


Get Time Difference between times

First you need intl package of flutter dart

import 'package:intl/intl.dart';

void main(){
  var format = DateFormat("HH:mm");
var one = format.parse("09:30");
var two = format.parse("13:20");
print("${two.difference(one)} Hours "); // prints 3:50 

Flutter datetime difference – App Example:

import 'package:flutter/material.dart';

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

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

class _HomeState extends State<Home> {

  Widget build(BuildContext context) {

    DateTime date1 = DateTime.parse("2022-05-30 11:47:00");
    DateTime date2 = DateTime.parse("2022-05-31 10:57:00");

    Duration diff = date1.difference(date2);

    return Scaffold(
         appBar: AppBar(
            title: Text("Calculate Difference between DateTime In Flutter App"),
            backgroundColor: Colors.redAccent,
          body: Container(
             padding: EdgeInsets.all(20),
             child: Column(
                      Text("First Date :" + date1.toString()),
                      Text("Second Date :" + date2.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()),