.net: How to parse a date with this format: 08 Feb

2020-02-01 23:37发布

How do I use DateTime.Parse to parse a datetime with the following format:

08 Feb 2011 06:46

In response to the answer I've received so far, I tried the following:

item.ServerDate = DateTime.ParseExact
                ("08 Feb 2011 06:46", "dd MMM yyyy hh:mm", System.Globalization.CultureInfo.InvariantCulture);

I still get the exception: String was not recognized as a valid DateTime.

UPDATE: The following code works without the hour and minute:

DateTime.ParseExact("08 Feb 2011","dd MMM yyyy",null)

标签: .net datetime
3条回答
beautiful°
2楼-- · 2020-02-01 23:45

DateTime.ParseExact might work for you: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

查看更多
够拽才男人
3楼-- · 2020-02-01 23:45

From the documentation:

"hh": The hour, using a 12-hour clock from 01 to 12.
"HH": The hour, using a 24-hour clock from 00 to 23.

and

In the .NET Framework 4, the ParseExact method throws a FormatException if the string to be parsed contains an hour component and an AM/PM designator that are not in agreement. In the .NET Framework 3.5 and earlier versions, the AM/PM designator is ignored.

So try replacing "hh" by "HH" in your format specifier, ie try "dd MMM yyyy HH:mm"

查看更多
倾城 Initia
4楼-- · 2020-02-01 23:47

DateTime.ParseExact("08 Feb 2011 06:46", "dd MMM yyyy hh:mm", 
    System.Globalization.CultureInfo.InvariantCulture);

In your question's sample code, you forgot to capitalize all of the month "M"s.

Edit

As Anton points out, the "H"s also need to be capitalized to use military time.

DateTime.ParseExact("08 Feb 2011 13:46", "dd MMM yyyy HH:mm", 
    System.Globalization.CultureInfo.InvariantCulture)

The above code works for me. I can't imagine why you'd get an error on the same code, when we're specifying the culture. Can you double-check your code and inputs?

查看更多
登录 后发表回答