简体   繁体   English

DateTime.TryParse 即使在设置时也能作为不同的文化工作

[英]DateTime.TryParse works as different cultures even when set

So my string dateRangeStart goes in the format 2019-01-31 ie 31st Jan 2019所以我的字符串dateRangeStart采用格式2019-01-31即 31st Jan 2019

IFormatProvider culture = new CultureInfo("en-UK", true);
if (!string.IsNullOrEmpty(dateRangeStart))
{
    DateTime d = new DateTime();
    if(DateTime.TryParse(dateRangeStart, culture, DateTimeStyles.None, out d))
    {
        /// whatever
    }
}

Using the same routine, if I put in 31-01-2019 - it fails to parse.使用相同的例程,如果我输入31-01-2019 - 它无法解析。 Why?为什么? I've told it that it's a UK date?我已经告诉它这是英国约会? Can it not recognise dd-MM-yyyy formats?!它不能识别dd-MM-yyyy格式吗?! but totally ok with MM-dd-yyyy ?MM-dd-yyyy

Also happens if I swap culture for CultureInfo.InvariantCulture如果我将culture交换为CultureInfo.InvariantCulture也会发生

Instead of TryParse , use TryParseExact .代替TryParse ,使用TryParseExact This way, you have full control over the string representation format you're attempting to parse:这样,您就可以完全控制您尝试解析的字符串表示格式:

if (!string.IsNullOrEmpty(dateRangeStart))
{
    DateTime d;
    if(DateTime.TryParseExact(dateRangeStart, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out d))
    {
        /// whatever
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM