What is the best way to convert an HH:MM:SS format string to an integer in minutes?
For example "01:10:00"
would give me an integer of 70.
It would round down so "01:10:30"
would also give me 70.
CodePudding user response:
You can try this below snippet to convert string to minutes:
String string = "01:10:00"; //string in duration format
int hour = int.parse(string.split(":")[0]); //extracting hours from string
int minute = int.parse(string.split(":")[1]); //extracting minutes
int second = int.parse(string.split(":")[2]); //extracting seconds
Duration duration = Duration(hours: hour, minutes: minute, seconds: second); //creating duration out of hour, min & seconds
print("Minutes is: ${duration.inMinutes}"); //finally printing the minutes
CodePudding user response:
final String time = '01:10:00'; // your time string
final parts = time.split(':').map((e) => int.parse(e)).toList(); // split the time string by colon as separator and then parse each splitted string to int using the map method.
final minutes = Duration(hours: parts[0], minutes: parts[1], seconds: parts[2])
.inMinutes; // create a duration instance from the splitted time (hours, minutes and seconds) and then use .inMinutes to get the duration in minutes
log(minutes.toString()); // 70
CodePudding user response:
Another alternative, that also handle that the string cannot be split properly and the text between the :
cannot be parsed to int
is as below. The other solutions would fail with index out of bounds exceptions and potentially FormatException when failing to parse the int.
Do as this if you want to avoid creating the unnecessary Duration object:
final match = RegExp(r'(\d ):(\d ):(\d )').firstMatch("01:10:00");
final minutes = match == null
? 0
: 60 * int.parse(match.group(1)!)
int.parse(match.group(2)!)
int.parse(match.group(3)!) ~/ 60;
OR as this if you want the Duration object:
final match = RegExp(r'(\d ):(\d ):(\d )').firstMatch("01:10:00");
final minutes = match == null
? 0
: Duration(
hours: int.parse(match.group(1)!),
minutes: int.parse(match.group(2)!),
seconds: int.parse(match.group(3)!),
).inMinutes;
OR