How to get Difference of Two Dates in Weeks, Months and Years in Flutter

Hi Guys, Welcome Flutterfever.com. 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.

You can find the difference between two dates in weeks, months, and years without using any package or plugin with the code below:

DateTime mytime = DateTime.now().subtract(Duration(hours: 23456));
print(mytime); //2020-05-07 06:56:55.501654
print(DateTime.now()); ////2023-01-09 14:56:55.510348

Duration diff = DateTime.now().difference(mytime);
int diffyears1 = (diff.inDays / 365).toInt();
int diffmonths1 = (diff.inDays / 30).toInt();
int diffweeks1 = (diff.inDays / 7).toInt();

print(diffyears1); //Output: 2
print(diffmonths1); //Output: 32
print(diffweeks1); //Output: 139
Here, years, months, and weeks are different, and not combined altogether.

Get Time Difference between times

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 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(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:[
         
                      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()),

                ]
             ),
          )
      );
  }
}

Just copy and use to:

https://github.com/coderbaba0/calculateage-fromdate-diffrence

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More