Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the default input format on the DateTime model binder in .Net MVC?

Tags:

c#

asp.net-mvc

I have a fairly standard .Net MVC Controller method:

public ActionResult Add(Customer cust) {  
  //do something...  
  return View();
}

Where Customer is something like:

public class Customer {
  public DateTime DateOfBirth { get; set; }
  //more stuff...
}

And a page containing:

<div><%= Html.TextBox("DateOfBirth") %></div>

The problem is my site is located on a US server so the cust.DateOfBirth is parsed in the US format MM/dd/yyyy. However, I want the users to enter their date of birth in the UK format dd/MM/yyyy.

Can I change the default input format on the DateTime ModelBinder or do I have to create my own custom ModelBinder?

like image 581
David Glenn Avatar asked Jul 14 '09 12:07

David Glenn


People also ask

How do I change the default date format in C#?

var ci = new CultureInfo("en-US"); ci. DateTimeFormat. ShortDatePattern = "MM/dd/yyyy"; app.

What is the default DateTime format in C #?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.


1 Answers

You can change the culture in the web.config file or at the page level. If you only want to change the date format and not the other aspects of the culture, though, that may require that you modify the current culture's DateTimeFormat via code in global.asax or a common base controller and set it to the DateTimeFormat for "en-GB".

Reference

To set the UI culture and culture for all pages, add a globalization section to the Web.config file, and then set the uiculture and culture attributes, as shown in the following example:

<globalization uiCulture="en" culture="en-GB" />

To set the UI culture and culture for an individual page, set the Culture and UICulture attributes of the @ Page directive, as shown in the following example:

<%@ Page UICulture="en" Culture="en-GB" %>

To have ASP.NET set the UI culture and culture to the first language that is specified in the current browser settings, set UICulture and Culture to auto. Alternatively, you can set this value to auto:culture_info_name, where culture_info_name is a culture name. For a list of culture names, see CultureInfo. You can make this setting either in the @ Page directive or Web.config file.

Alternative:

 CultureInfo.CurrentUICulture.DateTimeFormat
     = CultureInfo.CurrentCulture.DateTimeFormat
     = new CultureInfo( "en-GB", false ).DateTimeFormat;
like image 106
tvanfosson Avatar answered Oct 05 '22 22:10

tvanfosson