Find the number of days between two dates

 Instead of rounding the computed number of days, you can ignore Daylight Saving Time in DateTime calculations by using UTC DateTime objects1. (UTC does not observe DST.)

To compute the difference in days between two dates, ignoring the time (and therefore also ignoring Daylight Saving adjustments and time zones), construct new UTC DateTime objects that explicitly use the same time of day:

/// Returns the number of calendar days between [later] and [earlier], ignoring
/// time of day.
///
/// Returns a positive number if [later] occurs after [earlier].
int differenceInCalendarDays(DateTime later, DateTime earlier) {
  // Normalize [DateTime] objects to UTC and to discard time information.
  later = DateTime.utc(later.year, later.month, later.day);
  earlier = DateTime.utc(earlier.year, earlier.month, earlier.day);

  return later.difference(earlier).inDays;
}

1 Be aware that converting a locale DateTime object to UTC with .toUtc() will not help; dateTime and dateTime.toUtc() both represent the same moment in time, so dateTime1.difference(dateTime2) and dateTime1.toUtc().difference(dateTime.toUtc()) would return the same Duration.

Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime