加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – DateTime.ParseExact抛出System.FormatException

发布时间:2020-12-15 23:43:48 所属栏目:百科 来源:网络整理
导读:为什么这行代码有时会抛出System.FormatException? DateTime d = DateTime.ParseExact("01.07.2014","dd/MM/yyyy",CultureInfo.InvariantCulture); 解决方法 因为您的字符串和格式不匹配. 从documentation; Converts the specified string representation o
为什么这行代码有时会抛出System.FormatException?

DateTime d = DateTime.ParseExact("01.07.2014","dd/MM/yyyy",CultureInfo.InvariantCulture);

解决方法

因为您的字符串和格式不匹配.

从documentation;

Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.

请改用dd.MM.yyyy格式.

DateTime d = DateTime.ParseExact("01.07.2014","dd.MM.yyyy",CultureInfo.InvariantCulture);

这里是demonstration.

请记住,"/" custom format specifier在自定义日期和时间格式中具有特殊含义.它意味着;用我当前的文化日期分隔符替换我.

在你的个人资料中,它说你来自阿塞拜疆.这意味着你的CurrentCulture可能是az-Cyrl-AZ(西里尔文,阿塞拜疆)或az-Latn-AZ(拉丁文,阿塞拜疆).

实际上,在这种情况下你使用哪种文化并不重要,因为这两种文化都有.作为DateSeparator property.

这意味着您的原始代码也适用于您的CurrentCulture.

DateTime d = DateTime.ParseExact("01.07.2014",CultureInfo.CurrentCulture); 
                                 // or you can use null

有关更多信息,请查看;

> Custom Date and Time Format Strings

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读