How to convert a string containing AM/PM to DateTime?

后端 未结 4 2004
离开以前
离开以前 2020-12-20 11:59

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

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

4条回答
  •  生来不讨喜
    2020-12-20 12:36

    You can use the tt specifier:

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

    However be warned this can be locale specific. Also HH refers to the 24 hour clock, with AM/PM you generally use the 12 hour clock, so you'd want to use hh or just h for that.

提交回复
热议问题