.NET:如何解析日期格式为:2011年2月8日06:46格式为、日期、NET

由网友(别笑了眼泪都掉了)分享简介:我如何使用DateTime.Parse解析日期时间,格式如下:2011年2月8日06:46 在回应我到目前为止已经收到了答案,我试过如下:item.ServerDate = DateTime.ParseExact(2011年2月8日06:46,DD MMM YYYY HH:MM,System.Globalizatio...

我如何使用DateTime.Parse解析日期时间,格式如下:

2011年2月8日06:46

在回应我到目前为止已经收到了答案,我试过如下:

  item.ServerDate = DateTime.ParseExact
                (2011年2月8日06:46,DD MMM YYYY HH:MM,System.Globalization.CultureInfo.InvariantCulture);
 

我仍然得到了异常:字符串未被识别为有效的DateTime。

更新:无小时和分钟以下code作品:

  DateTime.ParseExact(2011年2月8日,DD MMM YYYY,NULL)
 

解决方案

  DateTime.ParseExact(2011年2月8日06:46,DD MMM YYYY HH:MM,
    System.Globalization.CultureInfo.InvariantCulture);
 

在你的问题的样本code,你忘了所有大写月的MS。

修改

由于安东指出,HS也需要资本使用军用时间。

  DateTime.ParseExact(2011年2月8日13:46,DD MMM YYYY HH:MM,
    System.Globalization.CultureInfo.InvariantCulture)
 

以上code对我的作品。我无法想象,为什么你会得到相同的code错误,当我们指定的文化。你能仔细检查你的code和投入?

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)

解决方案

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?

阅读全文

相关推荐

最新文章