Reputation: 12727
I'm struggling myself trying to find an easy way to change the DateTime format for my Table field.
I have a Model called Article with a field called releaseDate that is a DateTime
I managed to do it (visually) by converting the
Article.releaseDate.ToString("dd/MM/yy")
but the thing is when I try to submit a date with this format from the create action it returns an error telling the the format is wrong.
Any easy way to change the default ("MM/dd/yy") to ("dd/MM/yy")?
Thanks in advance
Upvotes: 3
Views: 5012
Reputation: 24532
You could change the culture information on a page by page basis by including
<%@ Page UICulture="en" Culture="en-GB" %>
or globally across all pages by adding to your web.config
<globalization uiCulture="en" culture="en-GB" />
Both will change the DateTime model binding to dd/MM/yyyy so no conversion is necessary.
See this question for more information
The code equivalent is
CultureInfo.CurrentUICulture.DateTimeFormat
= CultureInfo.CurrentCulture.DateTimeFormat
= new CultureInfo( "en-GB", false ).DateTimeFormat;
Upvotes: 5
Reputation: 60674
Your problem here is that since the compiler only sees two digits/two digits/two digits
in both cases, it has no way to know that you want day/month/year
instead of month/day/year
until it tries to actually casts, and notices that your value for the month is >= 12
.
You could solve this by splitting the date on /
, and throwing in the arguments in the "correct" order to the compiler, like so:
string[] dateParts = input.Split("/");
int day; int month; int year;
// You could use a boolean variable here to double-check that all casts are successful
Int32.TryParse(dateParts[0], out day);
Int32.TryParse(dateParts[1], out month);
Int32.TryParse(dateParts[2], out year);
var output = new DateTime(year, month, day);
If you put this in a separate function you could use it like this to support both formats:
DateTime releaseDate;
try
{
// will throw exception if input is not in the default format
releaseDate = new DateTime(input);
}
catch (InvalidFormatException ex)
{
releaseDate = GetDateTimeFromNonStandardInput(input);
}
catch
{
throw; // or do whatever error handling you feel like.
}
Personally, I'd write the GetDateTimeFromNonStandardInput()
as an extension method to the DateTime
class.
Upvotes: 0
Reputation: 87087
Yep. It sure is mate :)
try changing the current thread's CULTURE. By default, it takes the system's OS. but u can override that.
check this out...
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
Here's a good post explaining ....
HTH.
Upvotes: 3