DateTime.TryParse不同的结果 [英] DateTime.TryParse different results

查看:124
本文介绍了DateTime.TryParse不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为应用程序单元测试的一部分,我检查了一些日期时间字符串以获取其解析能力。我最近注意到一台机器上的字符串 0-02-20 11:36 可以解析为 {2000-02-20 11: 36:00} 通过 DateTime.TryParse(dateString,outsparedTimeStamp)而在其他计算机上则不能。

As part of my unittests for an application I check a few datetime strings for their ability to get parsed. I recently noticed that on one machine the string "0-02-20 11:36" can get parsed to {2000-02-20 11:36:00} by DateTime.TryParse(dateString, out parsedTimeStamp) while on other machines it can't.

string dt = "0-02-20 11:36";
DateTime parsedTimeStamp;
DateTime.TryParse(dateString, out parsedTimeStamp);
Console.WriteLine(parsedTimeStamp);


推荐答案

解析 DateTime 与文化相关的

我认为在特殊的机器上,文化设置使用 yyyy-MM-dd 格式,而在其他计算机上,日期格式为 MM-dd-yyyy

I would assume that on the exceptional machine, the culture settings use a yyyy-MM-dd format, while on the other machines, the date format was MM-dd-yyyy.

要解决此问题,您可以解析特定的文化或使用不变文化。

To work around this, you can parse in a specific culture or using an invariant culture.

DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedTimeStamp);






事实证明其中有很多文化:


It turns out there are quite a few of these cultures:

foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
    if (c.DateTimeFormat.ShortDatePattern == "yyyy-MM-dd")
    {
        Console.WriteLine("{0}: {1}", c.DisplayName, c.DateTimeFormat.ShortDatePattern);
    }
}







Korean: yyyy-MM-dd  
Polish: yyyy-MM-dd  
Albanian: yyyy-MM-dd  
Swedish: yyyy-MM-dd  
Khmer: yyyy-MM-dd  
Sinhala: yyyy-MM-dd  
Korean (Korea): yyyy-MM-dd  
Polish (Poland): yyyy-MM-dd  
Albanian (Albania): yyyy-MM-dd  
Swedish (Sweden): yyyy-MM-dd  
Khmer (Cambodia): yyyy-MM-dd  
Sinhala (Sri Lanka): yyyy-MM-dd  
Sami, Northern (Sweden): yyyy-MM-dd  
French (Canada): yyyy-MM-dd  
Sami, Lule (Sweden): yyyy-MM-dd  
Sami, Southern (Sweden): yyyy-MM-dd  
Sami (Southern): yyyy-MM-dd  
Sami (Lule): yyyy-MM-dd  

这篇关于DateTime.TryParse不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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