如何在Flutter中将String转换为TimeOfDay?

Dan*_*dez 3 dart flutter

我有一个字符串,可以说“ 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)

  • “DateFormat”是“intl”包的一部分。很高兴将其添加到答案中。包可以在这里找到:https://pub.dev/packages/intl (3认同)

z3r*_*_2k 8

01leo的答案有问题。小时和分钟参数应该为整数...因此,

TimeOfDay _startTime = TimeOfDay(hour:int.parse(s.split(":")[0]),minute: int.parse(s.split(":")[1]));
Run Code Online (Sandbox Code Playgroud)

这对我有用。

  • 当我们有以下格式的时间 10:00 PM 时,这不起作用 (2认同)

Leo*_* Nx 5

您可以执行以下操作:

TimeOfDay time = TimeOfDay(hour: s.split(":")[0], minute: s.split(":")[1]);
Run Code Online (Sandbox Code Playgroud)

s 是您想要转换的字符串。


Sha*_*nks 5

我在这里使用了一些答案,当 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)


Oma*_*ury 5

对于新手或初学者来说,这可能看起来很忙,但是您可以轻松地将 String 转换为 String DateTime,然后使用专门的构造函数DateTime进行转换,详细信息请参见此处TimeOfDay


请按照以下步骤进行无缝转换,而不会造成任何混乱:

  1. 将此包添加到pubspec.yamlintl

该包是将任何日期字符串转换为有效的 DateTime 对象所必需的。

  1. 将日期字符串转换为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字符串参考,请点击此链接