The following Line will give the current time
TimeOfDay _time = TimeOfDay.now(); //12:42
I want to add or remove 2 hours and 10 minutes from _time // i.e. 12:52 Or 10:52..etc
I had same need, then I have checked source of another library on Kotlin, ported their solution as following:
extension TimeOfDayExtension on TimeOfDay {
// Ported from org.threeten.bp;
TimeOfDay plusMinutes(int minutes) {
if (minutes == 0) {
return this;
} else {
int mofd = this.hour * 60 + this.minute;
int newMofd = ((minutes % 1440) + mofd + 1440) % 1440;
if (mofd == newMofd) {
return this;
} else {
int newHour = newMofd ~/ 60;
int newMinute = newMofd % 60;
return TimeOfDay(hour: newHour, minute: newMinute);
}
}
}
}
Other solutions does not take into account of exceeding 60 mins, or 24 hours. Trying to add 1 minute to 23:59
will cause crash. However this one safely casts it to 00:00
.
TimeOfDay _time = TimeOfDay.now();
we can do it like this
TimeOfDay newTime = _time.replacing(
hour: _time.hour - 2,
minute: _time.minute
);
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