nikodz
nikodz

Reputation: 727

ASP.NET MVC3 datetime format

I have MVC3 project with Entity. I have Data Annotation on DateTime property with DisplayFormat(DataFormatString="{0:dd/MM/yyyy hh:mm:ss}")

Controller with method which has entity as argument and calling view with same entity object, which displaying its date property.

So, I open browser and enter link http://site/entity/method?dateproperty=01/09/2012 01:02:03 (1 September 2012) and it displays 09/01/2012 01:02:03 (9 January 2012).

In view I'm using DisplayFor it's displaying like dd/MM/yyyy as I have a set DisplayFormat.

Problem is that it's reading like MM/dd/yyyy instead of dd/MM/yyyy, any solution?

P.S. I have tried globalization in web.config <sysmte.web> but didn't help.

Upvotes: 2

Views: 2840

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499840

I suspect the problem is that you haven't specified ApplyFormatInEditMode = true in your attribute, so it's parsing using the default format, but formatting with the format you're specifying.

I'm not an MVC dev by any means, but if you want the same format to be used in both directions, I believe you can just change your attribute to:

[DisplayFormat(ApplyFormatInEditMode = true, 
               DataFormatString="{0:dd/MM/yyyy HH:mm:ss}")]

Note that I've changed hh to HH, as I suspect you want a 24-hour format. I'd actually suggest using yyyy-MM-ddTHH:mm:ss (ISO-8601) as a less ambiguous format for the URL parameter - with a more user-centric display format, of course.

Upvotes: 2

Related Questions