如何转换字符串“ 07:35”; (HH:MM)到时间跨度 [英] How to Convert string "07:35" (HH:MM) to TimeSpan

查看:51
本文介绍了如何转换字符串“ 07:35”; (HH:MM)到时间跨度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将24小时制的格式化字符串转换为TimeSpan。

I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.

现在我有一种旧时尚风格 :

Right now I have a "old fashion style":

string stringTime = "07:35";
string[] values = stringTime.Split(':');

TimeSpan ts = new TimeSpan(values[0], values[1], 0);


推荐答案

在纠正此问题的同时:

TimeSpan time = TimeSpan.Parse("07:35");

如果您使用它进行验证...

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

请考虑 TimeSpan 主要用于经过的时间,而不是时间的天。它将接受大于24小时的值,并且还将接受负值。

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

如果您需要验证输入字符串是否是有效的时间(> = 00:00并且< 24:00),那么您应该考虑而是:

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

作为附加的好处,当包含AM或PM时,这还将解析12小时格式的时间,只要您提供适当的格式字符串,例如 h:mm tt

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

这篇关于如何转换字符串“ 07:35”; (HH:MM)到时间跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆