将日期格式解析为特定文化的格式

3

我居住在南非,使用en-ZA文化,我们的日期格式采用dd/mm/yyyy格式输入。

我有一个视图接受一个模型:

public class UserInfoModel
{
    public DateTime DateOfBirth{get;set;}
    // some other properties here
}

当用户输入日期 ie:04/15/1981,我在我的post方法中得到的日期时间是1981年4月15日,然而,当插入以下日期15/04/1981时,模型中的DateOfBirth属性返回null
有没有一种方法可以全局更改日期的解析方式(在我的整个应用程序中)?
我在web.config中添加了以下内容:
<system.web>
  <globalization culture="en-ZA" uiCulture="en-ZA"/>
</system.web>

但这似乎没有什么区别。


哪个模型为空?UserInfoModel吗? - Darin Dimitrov
更新了问题... 模型中只有 DateOfBirth 属性为空。 - stoic
2个回答

7
尝试将以下内容添加到您的GlobalAsax.cs文件中(位于App_code目录中):
protected void Application_BeginRequest(object sender, EventArgs e)
{
    CultureInfo cInfo = new CultureInfo("en-ZA");
    cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
    cInfo.DateTimeFormat.DateSeparator = "/";
    Thread.CurrentThread.CurrentCulture = cInfo;
    Thread.CurrentThread.CurrentUICulture = cInfo;
}

运行得很好...谢谢,奇怪的是在web.config中的条目没有任何影响。 - stoic

1
你可以使用扩展方法,例如:
public static class StringExt 
{
    public static DateTime ParseToDateTimeMyWay(this string iString)
    {
        DateTime dt;
        DateTime.TryParseExact(iString, "dd/MM/yyyy", System.Threading.Thread.CurrentThread.CurrentCulture, System.Globalization.DateTimeStyles.None, out dt);
        return dt;
    }
}

"04/15/1981".ParseToDateTimeMyWay(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接