开发者

Parsing Date Format to specific culture

I live in south Africa culture en-ZA, our date formats are inputted in format dd/mm/yyyy

I have a view that accepts a model:

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

When a user inputs the date ie: 04/15/1981 the datetime i get in my post method is 15 April 1981, however, when the following date is inserted 15/04/1981 the DateOfBirth property in the model returned is null

Is开发者_开发百科 there a way i can change the way that the date is being parsed globally(throughout my application)

I added to my web.config the following:

<system.web>
  <globalization culture="en-ZA" uiCulture="en-ZA"/>
</system.web>

But it does not seem to make a difference.


try to add this to your GlobalAsax.cs (located in your App_code directory)

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;
}


You could use the Extension Methods e.g.

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(); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜