DateTime.Parse抛出异常在C# [英] DateTime.Parse throw exception in C#

查看:685
本文介绍了DateTime.Parse抛出异常在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么异常被抛出,这里的工作code:

I have no idea why exception was thrown, here's the working code:

DateTime.Parse("1/12/2012 12:00:00 AM")

这是它抛出的异常之一:

And this is the one which throw exception:

DateTime.Parse("1/13/2012 12:00:00 AM")

抛出的异常是出现FormatException的,包括与此消息: 字符串未被识别为有效的DateTime。

Exception thrown is "FormatException", include with this message: "String was not recognized as a valid DateTime."

这里的的CurrentCulture值:

Here's the CurrentCulture value:

System.Globalization.CultureInfo.CurrentCulture
{en-MY}
Calendar: {System.Globalization.GregorianCalendar}
CompareInfo: {CompareInfo - en-MY}
CultureTypes: SpecificCultures | InstalledWin32Cultures
DateTimeFormat: {System.Globalization.DateTimeFormatInfo}
DisplayName: "English (Malaysia)"
EnglishName: "English (Malaysia)"
IetfLanguageTag: "en-MY"
IsNeutralCulture: false
IsReadOnly: true
KeyboardLayoutId: 17417
LCID: 17417
Name: "en-MY"
NativeName: "English (Malaysia)"
NumberFormat: {System.Globalization.NumberFormatInfo}
OptionalCalendars: {System.Globalization.Calendar[2]}
Parent: {en}
TextInfo: {TextInfo - en-MY}
ThreeLetterISOLanguageName: "eng"
ThreeLetterWindowsLanguageName: "ENM"
TwoLetterISOLanguageName: "en"
UseUserOverride: true

任何人都知道是怎么回事?

Anyone know what is going on here?

推荐答案

由于有一年只有12个月)

Because there are only 12 months in a year ;)

我猜你的当前区域性设置使用DD / MM / YYYY。无论你使用的字符串指定哪些文化的日期格式,使用解析超负荷解析:

I'm guessing your current culture setting uses 'dd/MM/yyyy'. Either specify which culture's date format you're using for the string to be parsed using the overload of Parse:

DateTime.Parse(String, IFormatProvider) 

或使用ParseExact()方法,并指定格式的自己。

or use the ParseExact() method and specify the format yourself.

var provider = CultureInfo.InvariantCulture;
var format = "M/dd/yyyy hh:mm:ss tt";

DateTime.ParseExact("1/13/2012 12:00:00 AM", format, provider);

这篇关于DateTime.Parse抛出异常在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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