DateTime.TryParseExact似乎无法识别字符串中的中文AM和PM指示符 [英] DateTime.TryParseExact doesn't seem to be recognizing chinese AM and PM designator characters within a string

查看:75
本文介绍了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指示符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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