我的时间是16:23:01。我尝试使用DateTime.ParseExact
,但无法正常工作。
这是我的代码:
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。
“ 16:23:01”与“ hh:mm:ss tt”的模式不匹配-它没有am / pm指示符,并且显然16点不在12小时制中。您需要在解析部分中指定该格式,因此您需要匹配现有数据的格式。你要:
DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
CultureInfo.InvariantCulture);
(请注意不变文化,而不是当前文化-假设您的输入确实始终使用冒号。)
如果要将其格式化为hh:mm:ss tt
,则需要将该部分放入ToString
调用中:
lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
或者更好的是(IMO)使用“无论哪种长时间的文化模式”:
lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);
还要注意,这hh
是不寻常的。通常,对于小于10的数字,您不想在数字上左按0。
(也可以考虑使用我的Noda Time API,该API具有一种LocalTime
类型-仅在“一天中的时间”更匹配)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句