Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart : How To add or Subtract Hours and minutes to TimeOfDay

Tags:

flutter

dart

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

like image 601
Pravin Shinde Avatar asked Jan 11 '20 07:01

Pravin Shinde


2 Answers

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.

like image 120
guness Avatar answered Nov 15 '22 18:11

guness


TimeOfDay _time = TimeOfDay.now();

we can do it like this

TimeOfDay newTime = _time.replacing(
        hour: _time.hour - 2,
        minute: _time.minute
      );
like image 37
Pravin Shinde Avatar answered Nov 15 '22 19:11

Pravin Shinde