DateTime.TryParseExact似乎无法识别字符串中的AM和PM指示符中文

编程入门 行业动态 更新时间:2024-10-18 14:16:15
本文介绍了DateTime.TryParseExact似乎无法识别字符串中的AM和PM指示符中文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试解析包含中文AM或PM字符的日期和时间字符串,如下所示.由于某种原因,DateTime.TryParse方法可以在正确的日期和时间获取,但是当我尝试使用DateTime.TryParseExact方法(在我看来是正确的格式说明符/掩码)时,解析失败,如下所示我剩下的是dateExact变量的默认值.

I'm trying to parse date and time strings that contain either Chinese AM or PM characters as below. For some reason, the DateTime.TryParse method can get at the correct date and time, but when I try to use the DateTime.TryParseExact method, with what looks to me to be a correct format specifier/mask, the parse fails as shown below where I'm left with a default value for the dateExact variable.

代码如下:

var dateString = "2018/2/9 下午 03:55:17"; DateTime date = default(DateTime); DateTime dateExact = default(DateTime); // this works DateTime.TryParse(dateString, new CultureInfo("zh-CHS"), DateTimeStyles.None, out date); // this doesn't work DateTime.TryParseExact(dateString, "yyyy/M/d tt HH:mm:ss", new CultureInfo("zh-CHS"), DateTimeStyles.None, out dateExact); Console.WriteLine("Date: " + date); Console.WriteLine("DateExact: " + dateExact);

这是输出:

日期:2018/2/9下午3:55:17

Date: 2/9/2018 3:55:17 PM

DateExact:1/1/0001 12:00:00 AM

DateExact: 1/1/0001 12:00:00 AM

推荐答案

"HH"表示24小时制的小时.当您指示时间在PM时,则24小时制的03:55:17必须在AM中.

"HH" denotes an hour in 24-hour format. While you're indicating the time is in the PM, 03:55:17 in 24-hour format must be in the AM

以下对我来说很好:

var dateString = "2018/2/9 下午 03:55:17"; DateTime dateExact = default(DateTime); DateTime.TryParseExact(dateString, "yyyy/M/d tt hh:mm:ss", new System.Globalization.CultureInfo("zh-CHS"), System.Globalization.DateTimeStyles.None, out dateExact); System.Console.Write(dateExact.ToString());

请注意使用"hh"而不是"HH"

Note the usage of "hh" instead of "HH"

据我所知,这与中文日期无关,以下内容无法解析:

This has nothing to do with Chinese dates as far as I can tell, the following fails to parse:

var dateString = "2018/2/9 PM 03:55:17"; DateTime dateExact = default(DateTime); var result = DateTime.TryParseExact(dateString, "yyyy/M/d tt HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateExact); System.Console.WriteLine(result.ToString()); System.Console.WriteLine(dateExact.ToString());

在将字符串更改为"2018/2/9 AM 03:55:17"(或"2018/2/9 PM 15:55:17")时,它将导致成功

while changing the string to "2018/2/9 AM 03:55:17" (or "2018/2/9 PM 15:55:17") will cause it to succeed

更多推荐

DateTime.TryParseExact似乎无法识别字符串中的AM和PM指示符中文

本文发布于:2023-11-07 19:43:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中文   指示   无法识别   DateTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!