如何将包含AM / PM的字符串转换为DateTime? [英] How to convert a string containing AM/PM to DateTime?

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

问题描述

我如何解析这样的字符串: 2/22/2015 9:54:02 AM到DateTime实例?

How can i parse a string like this: "2/22/2015 9:54:02 AM" to a DateTime instance?

我当前正在使用DateTime.ParseExact方法,但不包含AM / PM
,即:

i am currently using the DateTime.ParseExact method but without the AM/PM i.e:

 DateTime.ParseExact("2/22/2015 9:54:02", "M/dd/yyyy HH:mm:ss")

I希望也能够解析AM / PM符号。

I would like to be able to parse the AM/PM signs as well.

推荐答案

您应更改小时格式( H )转换为小写:

You should change the hour format (H) to lowercase like this:

DateTime.ParseExact("2/22/2015 9:54:02 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

大写字母 H表示24小时制,小写字母 h表示12小时制将遵循候选字符串中的AM / PM。

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

这篇关于如何将包含AM / PM的字符串转换为DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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