DateTime.TryParseExact()拒绝有效格式 [英] DateTime.TryParseExact() rejecting valid formats

查看:102
本文介绍了DateTime.TryParseExact()拒绝有效格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析 ASP.NET WebForms 页面中的DateTime值,并且日期字符串不断被 DateTime.TryParseExact()拒绝。 方法,即使它显然与提供的格式字符串之一匹配。

I'm parsing a DateTime value in an ASP.NET WebForms page and the date string keeps getting rejected by the DateTime.TryParseExact() method even though it clearly matches one of the supplied format strings.

它似乎在我的开发机器上无法正常运行,但可以在生产服务器上工作,因此我正在考虑涉及本地日期设置,但是即使我提供 IFormatProvider(CultureInfo)对象作为参数

It seems to fail on my development machine at home but work on the production server, so I am thinking of local date settings being involved, but this error occurs even when I supply an IFormatProvider (CultureInfo) object as a parameter

这是代码:

DateTime startDate;
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
                    "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy"};

var errStart = row.FindControl("errStartDate"); //my date format error message
if (!DateTime.TryParseExact(txtStartDate.Text, formats, null, DateTimeStyles.None, out startDate))
{
    errStart.Visible = true; //we get here even with a string like "20/08/2012"
    return false;
}
else
{
    errStart.Visible = false;
}

请注意,我给出的是 null FormatProvider 在上面,当我提供 CultureInfo 对象作为
(CultureInfo provider =新的CultureInfo( en-US))。

Note I'm giving a null FormatProvider in the above, but the same problem occurs when I provide a CultureInfo object as (CultureInfo provider = new CultureInfo("en-US")) for this parameter.

我缺少什么?

推荐答案

尝试:

 DateTime.TryParseExact(txtStartDate.Text, formats, 
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out startDate)

这篇关于DateTime.TryParseExact()拒绝有效格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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