我有一个字符串,可以说“ 16:00”,我想将其转换为TimeOfDay类型。我检查了文档,它仅提供从DateTime到TimeOfDay的转换程序,但是我找不到从String转换为TimeOfDay的方法。
小智 18
像这样:
TimeOfDay stringToTimeOfDay(String tod) {
final format = DateFormat.jm(); //"6:00 AM"
return TimeOfDay.fromDateTime(format.parse(tod));
}
Run Code Online (Sandbox Code Playgroud)
01leo的答案有问题。小时和分钟参数应该为整数...因此,
TimeOfDay _startTime = TimeOfDay(hour:int.parse(s.split(":")[0]),minute: int.parse(s.split(":")[1]));
Run Code Online (Sandbox Code Playgroud)
这对我有用。
您可以执行以下操作:
TimeOfDay time = TimeOfDay(hour: s.split(":")[0], minute: s.split(":")[1]);
Run Code Online (Sandbox Code Playgroud)
s 是您想要转换的字符串。
我在这里使用了一些答案,当 AM 和 PM 在字符串中时无法正常工作。这是我的解决方案。
TimeOfDay fromString(String time) {
int hh = 0;
if (time.endsWith('PM')) hh = 12;
time = time.split(' ')[0];
return TimeOfDay(
hour: hh + int.parse(time.split(":")[0]) % 24, // in case of a bad time format entered manually by the user
minute: int.parse(time.split(":")[1]) % 60,
);
}
Run Code Online (Sandbox Code Playgroud)
对于新手或初学者来说,这可能看起来很忙,但是您可以轻松地将 String 转换为 String DateTime,然后使用专门的构造函数DateTime进行转换,详细信息请参见此处。TimeOfDay
请按照以下步骤进行无缝转换,而不会造成任何混乱:
pubspec.yaml:intl。该包是将任何日期字符串转换为有效的 DateTime 对象所必需的。
DateTime对象,如下所示:
DateTime dateTime = DateFormat("h:mm a").parse(placement.startTime);
TimeOfDay timeOfDay = TimeOfDay.fromDateTime(dateTime)
你有它。但不要忘记DateFormat相应地更改您的字符串。对我来说,我的日期字符串是4:30 AM,所以我的DateFormat字符串是"h:mm a"。DateFormat根据需要更改字符串。对于DateFormat字符串参考,请点击此链接
| 归档时间: |
|
| 查看次数: |
1714 次 |
| 最近记录: |