C#中的DateTime.Parse抛出异常
发布时间:2020-12-16 00:19:04 所属栏目:百科 来源:网络整理
导读:我不知道为什么抛出异常,这是工作代码: DateTime.Parse("1/12/2012 12:00:00 AM") 这是抛出异常的那个: DateTime.Parse("1/13/2012 12:00:00 AM") 抛出的异常是“FormatException”,包含此消息: “字符串未被识别为有效的DateTime.” 这是CurrentCulture
我不知道为什么抛出异常,这是工作代码:
DateTime.Parse("1/12/2012 12:00:00 AM") 这是抛出异常的那个: DateTime.Parse("1/13/2012 12:00:00 AM") 抛出的异常是“FormatException”,包含此消息: 这是CurrentCulture值: 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 有谁知道这里发生了什么? 解决方法
因为一年只有12个月;)
我猜你当前的文化背景使用’dd / MM / yyyy’.使用Parse的重载指定要用于解析字符串的文化的日期格式: DateTime.Parse(String,IFormatProvider) 或者使用ParseExact()方法并自己指定格式. var provider = CultureInfo.InvariantCulture; var format = "M/dd/yyyy hh:mm:ss tt"; DateTime.ParseExact("1/13/2012 12:00:00 AM",format,provider); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |