Flutter double to Time in hours

Viewed 3790

I'm trying to convert a double value (e.g. 9.5) to a corresponding hour/minute value (e.g. 9.30). I also want to perform calculations using this value, but handle it like a time value (e.g. adding 23 and 2 should result in 1 as the hours should wrap around at 24 hours).

I already tried to convert the value to DateTime, but it says "invalid date format".

1 Answers

This should do it

void main() {
  print(getTimeStringFromDouble(9.5)); // 9:30
  print(getTimeStringFromDouble(25.0)); // 1:0
}

String getTimeStringFromDouble(double value) {
  if (value < 0) return 'Invalid Value';
  int flooredValue = value.floor();
  double decimalValue = value - flooredValue;
  String hourValue = getHourString(flooredValue);
  String minuteString = getMinuteString(decimalValue);

  return '$hourValue:$minuteString';
}

String getMinuteString(double decimalValue) {
  return '${(decimalValue * 60).toInt()}'.padLeft(2, '0');
}

String getHourString(int flooredValue) {
  return '${flooredValue % 24}'.padLeft(2, '0');
}

Related