0

I'm trying to ind the duration difference between two dates for the respective units in Dart. I'm looking at jiffy since it was inspired by moment.js and in moment.js that would be achieved by the following snippet:

const dateOne= moment('3/29/2020','M/D/YYYYY'); //29th March 2020
const currentDate = moment();
// get the difference between the moments
const diff = currentDate.diff(dateOne);
//express as a duration
const diffDuration = moment.duration(diff);

const diffDuration = {
  months: diffDuration.months(), //6 months
  days: diffDuration.days(), //14 days
  hours: diffDuration.hours(), //21 hours
  minutes: diffDuration.minutes(), //55 minutes
  seconds: diffDuration.seconds(), //44 seconds
}

But with Jiffy I can only find the difference, not the difference duration

var jiffy1 = Jiffy(); //get current time
var jiffy2 = Jiffy("2020-03-29", "yyyy-MM-dd");
var _months = jiffy1.diff(jiffy2, Units.MONTH); //6 
var _days = jiffy1.diff(jiffy2, Units.DAY); //197 days
var _hours = jiffy1.diff(jiffy2, Units.HOUR); //284,99 hours
var _seconds = jiffy1.diff(jiffy2, Units.SECOND );
var _minutes = jiffy1.diff(jiffy2, Units.MINUTE);

Is there any way to achieve that functionality in Dart (Flutter) it doesn't have to be with a package. I did consider the DateTime class but it seems to give the same output as well, just with less units avaliable

SRR
  • 1,608
  • 1
  • 21
  • 51
  • There are many answers to this, here is one: https://stackoverflow.com/questions/52713115/flutter-finding-difference-between-two-dates Datetime class and Duration class are the way to go – GrahamD Oct 13 '20 at 19:12
  • @GrahamD that gives the difference sure but I'm looking for the difference duration? I'm not sure if I'm phrasing that properly. Let's say I had a start date of March 1st and and end date of April 1st. The difference between those two is 32 days. But I want the final output to be 1 month 1 day. – SRR Oct 15 '20 at 00:48
  • Ok, I think I understand. Maybe this https://pub.dev/packages/simple_moment and this https://pub.dev/packages/date_util could help? – GrahamD Oct 15 '20 at 15:57
  • @GrahamD thanks! I'll give them a go and update this question as I go along – SRR Oct 15 '20 at 16:30
  • @GrahamD got the answer! – SRR Oct 22 '20 at 00:38

1 Answers1

0

With much thanks to Alex on this question I've resolved it using the time_machine package

import 'package:time_machine/time_machine.dart';
LocalDateTime a = LocalDateTime.now();
LocalDateTime b = LocalDateTime.dateTime(DateTime(2020, 3, 29, 0, 0, 0));
Period diff = a.periodSince(b);
var _months = diff.months;
var _days = diff.days;
var _hours = diff.hours;
var _seconds = diff.seconds;
var _minutes = diff.minutes;
print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}; hours: ${diff.hours}; minutes: ${diff.minutes}; seconds: ${diff.seconds}");

Don't forget to use LocalDateTime and not just LocalDate if you want the time difference as well

SRR
  • 1,608
  • 1
  • 21
  • 51