flutter 如何将HH:MM:SS STRING格式转换为以分钟为单位的整数?

ctzwtxfj  于 2022-11-25  发布在  Flutter
关注(0)|答案(3)|浏览(192)

将HH:MM:SS格式字符串转换为以分钟为单位的整数的最佳方法是什么?

例如,"01:10:00"会给出整数70。

它会向下舍入,所以"01:10:30"也会得到70。

5lhxktic

5lhxktic1#

您可以尝试以下代码段将字符串转换为分钟:

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
thigvfpy

thigvfpy2#

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
0md85ypi

0md85ypi3#

另一种解决方案也可以处理字符串不能被正确拆分以及:之间的文本不能被解析为int的情况,如下所示。其他解决方案将失败,并出现索引越界异常,并且在解析int失败时可能出现FormatException。
如果要避免创建不必要的Duration对象,请执行以下操作:

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;

如果您想要Duration对象,则OR为:

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;

相关问题