Bohdan Kuts Bohdan Kuts - 1 month ago 17
ASP.NET (C#) Question

How to set dateFormat for jQuery UI datepicker according to server date format?

I am using ASP.NET MVC and working with two servers. On first server (for testing) date format is set to
, but on second -
. The question is: is it possible to customize dateFormat for jQuery UI datepicker according to server date format where site is working?

Rendering date on view:


Javascript code example:

dateFormat: '',
onSelect: function (dateText) { doSomething(); },
onClose: function () { doAction(); }

Is it possible to replace strongly typed
dateFormat: ''
with something that will format date according to server date format? And if 'yes' - how to do it?

For now, I am using some temporary solution:

dateFormat: $("#myDate").val().indexOf('/') > 0 ? 'mm/dd/yy' : '',
onSelect: function (dateText) { doSomething(); },
onClose: function () { doAction(); }

Answer Source

You could enforce the format on your control i.e.

@Html.TextBoxFor(m => m.OrderDate, String.Format("{0:dd/M/yy}", Model.YourDate),
  new { @class = "datepicker datepicker-init" })

jQuery UI takes a slightly different date format i.e dd/mm/y not mm/dd/yy as in your question.

So this would work:

<script type="text/javascript">
            minDate: 0,
            dateFormat: 'dd/mm/y'


See here:

If that is no good you could determine the format, and set it on your ViewModel i.e.

<script type="text/javascript">
            minDate: 0,
            dateFormat: '@Model.MyDateFormat'



Ok, to determine if the date has a forwards slash you could do it as follows:

Create a string extension, which replaces them either way;

public static string ContainsForwardSlashReplace(this string aString)
    return aString.Contains("/") ? aString.Replace("/",".") : aString.Replace(".","/");

Then call this on your formatted date in your controller, for both your returned date and your jQueryUI format.

Here is a simple console example of a before and after:

var aDate = DateTime.Now.ToString("d");
    // Change below to the oposite that is returned from above to test to other way
    //var aDate = "23/01/2014";
    var jqueryUiFormat = "dd/mm/y";
string newDate = aDate.ContainsForwardSlashReplace();
string newjQueryUiFormat = jqueryUiFormat.ContainsForwardSlashReplace();
Console.WriteLine("Original Date: {0}", aDate);
Console.WriteLine("Replaced Date: {0}", newDate);
Console.WriteLine("Original jQueryFormat : {0}", jqueryUiFormat);
Console.WriteLine("Replaced jQueryFormat: {0}", newjQueryUiFormat);

The final piece is to add both the formated date and jQuery ui date format to your model and output it as I describe above.

UPDATE (by question author)

Seems there are no solution what I am looking for. So this one will be marked as solution. For more - see comments.