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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With