Flutter - Converting minutes into H:M
Asked Answered
D

2

12

I'm looking for a method to convert minutes into hours and minutes. I'm using the intl package through DateFormat but this requires both hours and minutes so it won't do.

If I have 100 minutes, I would like this to be converted to 01:40. Thanks

Dyandyana answered 6/7, 2019 at 23:9 Comment(0)
E
24

Does this work?

String durationToString(int minutes) {
    var d = Duration(minutes:minutes);
    List<String> parts = d.toString().split(':');
    return '${parts[0].padLeft(2, '0')}:${parts[1].padLeft(2, '0')}';
}

print(durationToString(100)); //returns 01:40
Esquibel answered 7/7, 2019 at 0:5 Comment(2)
I need to be able to pass a variable to this and I can't change d to int from Duration as I'm getting Only valid value is 0:1Dyandyana
@Dyandyana I updated it to be more in line with original ask. Hope it helps, otherwise I might need more info to understand the question.Esquibel
W
17

This will work for you


String getTimeString(int value) {
  final int hour = value ~/ 60;
  final int minutes = value % 60;
  return '${hour.toString().padLeft(2, "0")}:${minutes.toString().padLeft(2, "0")}';
}
Wallas answered 7/7, 2019 at 5:18 Comment(2)
Posted this before I saw socasanta's answer. It might be the better implementationWallas
Never knew about ~ or .padLeft(). Thanks.Coterminous

© 2022 - 2024 — McMap. All rights reserved.