简体   繁体   English

如何在 Flutter 中将字符串转换为时间

[英]How to Convert String to Time in Flutter

I am trying to convert DateTime to Time.我正在尝试将 DateTime 转换为时间。 I successfully converted it to a String using DateFormat but now i want to convert this String to Time (H,M,S).我使用 DateFormat 成功地将其转换为字符串,但现在我想将此字符串转换为时间(H、M、S)。 Is there a way to directly parse and convert the variable?有没有办法直接解析和转换变量?

In general Dart, there is no such thing as a Time object.一般Dart,没有Time object这样的东西。 In Flutter, though, you generally want to represent specific times (without a date component) with TimeOfDay .但是,在 Flutter 中,您通常希望使用TimeOfDay表示特定时间(没有日期组件)。 Unfortunately, it doesn't have a parse method for parsing timestamp strings, so the easiest way to get it is by passing in the DateTime you started with:不幸的是,它没有解析时间戳字符串的parse方法,因此获取它的最简单方法是传入您开始使用的DateTime

TimeOfDay time = TimeOfDay.fromDateTime(myDateTime);

If you also require the seconds component, unfortunately TimeOfDay doesn't support that.如果您还需要秒组件,不幸的是TimeOfDay不支持。 In that case, you will either have to create your own Time class or just use the DateTime time components directly.在这种情况下,您要么必须创建自己的Time class,要么直接使用DateTime时间组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM