flutter/dart duration difference in hours

Viewed 307

Hi there in my code i have to return if the date is older than 24 hours than it should return me the date and if not it should return me the difference in hours.

publishtime: DateTime.now().subtract(Duration(days: 10));

_getTime() {
       String time;
       DateTime now = DateTime.now();
       Duration difference = publishtime.difference(now);
   
       if (difference.inHours > 24) {
         var format = DateFormat("dd.MM.yyyy");
         time = format.format(publishtime);
       } else {
         time = difference.inHours.toString().replaceAll('-', '') + " hours ago";
       }
   return time;   
}

it returns me "240 hours ago" but it should return me the date

why dont the if (difference.inHours > 24) work as it should? the difference.inHours also return a int value so why dont it work?

2 Answers

The problem is here Duration difference = publishtime.difference(now); it should be Duration difference = now.difference(publishtime);

Or you can use abs() at your difference, same result.

As mentioned in the other answer, difference.inHours evaluates to -240, not 240. This is because the dates are the wrong way around to how you want them.

Related