将字符串转换为时间 [英] Convert string to Time

查看:64
本文介绍了将字符串转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的时间是16:23:01.我尝试使用 DateTime.ParseExact ,但无法正常工作.

I have a time that is 16:23:01. I tried using DateTime.ParseExact, but it's not working.

这是我的代码:

string Time = "16:23:01"; 
DateTime date = DateTime.ParseExact(Time, "hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);

lblClock.Text = date.ToString();

我希望它在标签上显示为04:23:01 PM.

I want it to show in the label as 04:23:01 PM.

推荐答案

"16:23:01"与"hh:mm:ss tt"的模式不匹配-它没有am/pm指示符,而16点显然不在12小时制内.您要在 parsing 部分中指定该格式,因此需要匹配现有数据的格式.您想要:

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(请注意不变的文化,不是当前的文化-假设您的输入确实总是使用冒号.)

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

如果您想将其 format 格式化为 hh:mm:ss tt ,则需要将该部分放入 ToString 调用中:

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

或者更好的是(IMO)使用无论哪种长期文化模式":

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

还请注意, hh 是不寻常的;通常,您不想要对数字小于10的数字进行左键填充.

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(也可以考虑使用我的 Noda Time API,该API具有 LocalTime 类型-一种更合适的匹配方式一天中的时间".)

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

这篇关于将字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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