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

In this example, we are going to show you how to find the difference between two dates in weeks, months, and years in Flutter. In dart, currently, there is no option to find differences in weeks, months, and years, there are only days, hours, minutes, and second.

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.

Now, add the Jiffy package to your project by adding the following lines at pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  jiffy: ^5.0.0

Now, use the code below:

import 'package:jiffy/jiffy.dart';
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

num diffyears = Jiffy(DateTime.now()).diff(mytime, Units.YEAR);
num diffmonths = Jiffy(DateTime.now()).diff(mytime, Units.MONTH);
num diffweeks = Jiffy(DateTime.now()).diff(mytime, Units.WEEK);

print(diffyears);  //Output: 2
print(diffmonths); //Output: 32
print(diffweeks); //Output: 139

Here, the years, months, and weeks are not combined.

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 days = diff.inDays;
int years = (days / 365).toInt();
int months =  ((days - (years * 365)) / 30).toInt();
int weeks = ((days - (years * 365 + months * 30)) / 7).toInt();

print(years); //Output: 2
print(months); //Output: 8
print(weeks); //Output: 1
//here is the combined difference on years, months and weeks

Here, the difference is 2 years, 8 months, and 1 week combined, on the above code the differences are different.

In this way, you can get difference between two dates in weeks, month and years.

 

No any Comments on this Article


Please Wait...