Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round time to the nearest quarter hour in Dart and Flutter?

I have a DateTime and would like to round it down to 15 seconds (or another interval).

e.g. "2020-03-16 12:23:53.756" to "2020-03-16 12:23:45.000"

and "2020-03-16 12:24:01.1234" to "2020-03-16 12:24:00.000"

like image 305
x23b5 Avatar asked Dec 06 '22 08:12

x23b5


1 Answers

You can do this in Dart and Flutter with an Extension on DateTime:

extension on DateTime{

  DateTime roundDown({Duration delta = const Duration(seconds: 15)}){
    return DateTime.fromMillisecondsSinceEpoch(
        this.millisecondsSinceEpoch -
        this.millisecondsSinceEpoch % delta.inMilliseconds
    );
  }
}

Usage:

DateTime roundedDateTime = DateTime.now().roundDown();
print(roundedDateTime);

Output: "2020-03-16 12:23:45.000"

or

DateTime roundedDateTime = DateTime.now().roundDown(delta: Duration(hour: 1));
print(roundedDateTime);

Output: "2020-03-16 12:00:00.000"

like image 117
x23b5 Avatar answered Jun 09 '23 05:06

x23b5