Sunday, 24 January 2016

DMY date formatting in asp.net MVC and Entity framework

Most DevOps types in the world have at some time been frustrated by date formatting and database collation. Its no wonder, given that the standard in most of the world is DMY with the exception being the country from which most software platforms and languages originate which uses MDY (see https://en.wikipedia.org/wiki/Date_format_by_country )  Its a problem that can cause real pain and is not always obvious as for the first 11 days of each month, you will not get any errors. I've had to deal with this one several times when moving apps between environments where the database collation is not updated correctly.

asp.net and Entity framework fortunately do make it a bit easier when developing software for the DMY and YMD parts of the world. There are two things that you need to do.

1) In the site web.config, add to <system.web>  an element like:
<globalization culture="en-AU" uiCulture="en-AU" />
(change the culture and  uiCulture to match your culture, this example is for Australia)


2) Add a date format attribute in the model class to present the correct format, for example:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime NextRenewalDate { get; set; }

Now all the server and client side validations will correctly validate dates using this format and the data in the database will also be in this format.

This works with asp.net version 5, in the community edition of Visual studio (downloaded at the end of 2015) For older projects, you may need to update some jQuery libraries. This post from stackoverflow may be helpful in that case - http://stackoverflow.com/questions/18548816/mvc-4-date-culture-issue 

No comments:

Post a Comment