ASP.NET MVC Date input format

Azizjan Hamidovich Ayupov

I have a textbox with date type:

 @Html.TextBoxFor(m => m.DateOfBirth, new { @class = "form-control", type = "date" })

of the model's field DateOfBirth

   [Required]
    [DataType(DataType.Date)]
    public DateTime DateOfBirth { get; set; } // Дата рождения

But date format is static mm/dd/yy which is wrong for Russian (dd/mm/yy). Of course I can set date format manually, but the system is multi-lingual and has English language as well as Russian, Kyrgyz, Uzbek (they all use European formats). When a user change a language

 Thread.CurrentThread.CurrentCulture =CultureInfo.CreateSpecificCulture(lang);
 Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);

He supposed to see appropriate date format. But somewhy it doesn't happen :(

I have explored that the format depends on the language the browser uses. But chrome can't be displayed in Kyrgyz language...

IPValverde

You can accomplish what you want using the jquery.ui datepicker. By using it (or any other library that provides a similar functionality) you can easily maintain a consistent UX across multiple browsers, while with the standard HTML5 date inputs (<input type="date" />) you'll have browser-specific behaviour.

You can simply set the datepicker "regional" when loading your page. It seems that one of your goals is to be able to address multiple languages, I would recommend sticking with the "localization" idea rather than just setting the dateFormat attribute. If jquery ui does not provide a localization for the culture you are looking for, create one.

I've created a simple example where you can see the localization working in client-side. The idea would be very similar, but in your case it would be in the server-side: https://jsfiddle.net/ipvalverde/wxLxLe7p/9/

Regarding ASP.net MVC, I would suggest you to create a Razor View to setup all your datepicker elements on screen with your culture info. Something like this:

@{
    _Layout = null;
}

var currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
string cultureCode = currentCulture.Name;

string datepickerLocalization = // Convert the thread culture name to datepicker culture name...

<script>
    $(function () {
      $.datepicker.setDefaults($.datepicker.regional["@datepickerLocalization"]);
    })
</script>

Make sure you have loaded the javascripts with localization for the supported languages.

Let me know if this helps.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related