0

For Example: Sunset-Sunrise.org provides sunset/sunrise time with HH:MM:SS format.

Given a time such as 12:53:57, I want to round the seconds to 12:54:00. Please advise.

omer
  • 522
  • 1
  • 8
  • 26

2 Answers2

3

A general technique for rounding is to add half of the unit you want to round to and then truncating. For example, if you want to round an integer to the nearest ten's digit, you can add 5 and discard the one's digit: ((x + 5) ~/ 10) * 10.

The same technique works for times too. You can first parse the HH:MM:SS string into a DateTime object. Then, to round the DateTime to the nearest minute, you can add 30 seconds and copy all of the resulting fields except for the seconds (and subseconds):

DateTime roundToMinute(DateTime dateTime) {
  dateTime = dateTime.add(const Duration(seconds: 30));
  return (dateTime.isUtc ? DateTime.utc : DateTime.new)(
    dateTime.year,
    dateTime.month,
    dateTime.day,
    dateTime.hour,
    dateTime.minute,
  );
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0

You can use date_time_fromat packages

from the docs

final timeOffset = dateTime.subtract(Duration(hours: 6, minutes: 45));

// 7 hours
print(DateTimeFormat.relative(timeOffset));

// 6 hours
print(DateTimeFormat.relative(timeOffset, round: false));

This is the URL

Nikhil Badyal
  • 1,589
  • 1
  • 9
  • 20