Flutter:从时间格式中删除前导零

sel*_*ted 5 time-format dart flutter

我收到这种格式的字符串'HH:mm:ss',我需要去掉前导零或将其转换为分钟/小时。有没有办法RegExp达到这个目的?

没有前导零的示例:

00:03:15 => 3:15
10:10:10 => 10:10:10
00:00:00 => 0:00
04:00:00 => 4:00:00
00:42:32 => 42:32
00:00:18 => 0:18
00:00:08 => 0:08
Run Code Online (Sandbox Code Playgroud)

时间转换为分钟/小时的示例

00:07:00 => 7 min
00:10:30 => 10:30 min
01:40:00 => 1h 40 min
Run Code Online (Sandbox Code Playgroud)

Tin*_*son 8

尝试以下操作

将 intl 包添加到您的 pubspec.yaml 文件中。

import 'package:intl/intl.dart';

DateFormat dateFormat = DateFormat("HH:mm");
Run Code Online (Sandbox Code Playgroud)

将日期时间对象转换为字符串

DateTime yourDate = DateTime.now());
String string = dateFormat.format(yourDate);
Run Code Online (Sandbox Code Playgroud)

也可以尝试这个

DateTime yourDate = DateTime.now();
String string =  new DateFormat.Hm().format(yourDate);    // force 24 hour time
Run Code Online (Sandbox Code Playgroud)

更新

要将字符串解析为日期,您可以使用它

DateFormat df = DateFormat('HH:mm:ss');
DateTime dt = df.parse('00:07:00');
String string = DateFormat.Hm().format(dt);
Run Code Online (Sandbox Code Playgroud)

参考


Gen*_* Bo 5

看起来此时只需在格式字符串中使用单个字符(例如,M而不是MM)即可处理前导零的修剪:

前:

// Output: 01/01/2021, 02:41 PM
static final dateFormatLeadingZeros = new DateFormat('MM/dd/yyyy, hh:mm a');
Run Code Online (Sandbox Code Playgroud)

后:

// Output: 1/1/2021, 2:41 PM
static final dateFormatTrimmed = new DateFormat('M/d/yyyy, h:mm a');
Run Code Online (Sandbox Code Playgroud)