为什么 DateTime.ParseExact() 不能使用“M'/'d'/'yyyy H':'mm':'ss'"解析“4/4/2010 4:20:00 PM"中的 AM/PMtt" [英] Why can’t DateTime.ParseExact() parse the AM/PM in “4/4/2010 4:20:00 PM” using “M'/'d'/'yyyy H':'mm':'ss' 'tt”

查看:15
本文介绍了为什么 DateTime.ParseExact() 不能使用“M'/'d'/'yyyy H':'mm':'ss'"解析“4/4/2010 4:20:00 PM"中的 AM/PMtt"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 c#,如果我这样做了

I'm using c#, and if I do

DateTime.ParseExact("4/4/2010 4:20:00 PM", "M'/'d'/'yyyy H':'mm':'ss' 'tt", null)

返回值总是 4:20 AM——我在使用 tt 时做错了什么?

The return value is always 4:20 AM -- what am I doing wrong with using tt?

谢谢!

推荐答案

使小时格式 (H) 小写如下:

Make the hour format (H) lowercase like this:

DateTime.ParseExact(
            "4/4/2010 4:20:00 PM", 
            "M/d/yyyy h:mm:ss tt", 
            CultureInfo.InvariantCulture);

大写的H"表示 24 小时制,小写的h"表示 12 小时制,将尊重候选字符串中的 AM/PM.

Uppercase "H" indicates 24-hour time and lowercase "h" indicates 12-hour time and will respect the AM/PM in the candidate string.

旁注:最好为这样的方法提供一个 IFormatProvider 实例(即使它只是 CultureInfo.InvariantCulture).这是在您遇到问题之前并不重要的事情之一,因此养成指定文化信息的习惯会很好.

Side note: It is best to provide an instance of IFormatProvider to methods like this (even if it's just CultureInfo.InvariantCulture). It's one of those things that doesn't really matter until you hit problems with it so it can be good to be in the habit of specifying culture information.

这篇关于为什么 DateTime.ParseExact() 不能使用“M'/'d'/'yyyy H':'mm':'ss'"解析“4/4/2010 4:20:00 PM"中的 AM/PMtt"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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