Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert .NET DateTimeFormatInfo to Javascript jQuery formatDate?

I hava a jQuery UI datepicker which I intend to use with a textbox in ASP.NET MVC. The date-display in the textbox is localized via CultureInfo and of course should be recognized by jquery to select the correct date in the datepicker:

<%= Html.TextBox("Date", Model.Date.ToString("d", currentCultureInfo),
    new { @class = "datepicker" })%>

What I am trying to do now is to initialize the datepicker with a dateformat like

string jsCode = @"$("".datepicker"").datepicker({
    dateFormat: '" + currentCultureInfo.DateTimeFormat.ShortDatePattern + @"',
});";

The Problem is that the format of the format string of DateTimeFormatInfo (see MSDN Link) is completely different to the format string in jQuery (jQuery formatDate).

https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx

Sample (German date format like 16.07.2009):

.NET: 'dd.MM.yyyy' should be converted to 'dd.mm.yy' in jQuery/Javascript

Is there a method or a library that does the needed transformation between the two formats?

like image 314
mattanja Avatar asked Jul 16 '09 16:07

mattanja


1 Answers

If only ShortDatePattern must be converted, the following code provides what I need:

public class wxDateTimeConvert
{
    /// <summary>
    /// Gets the javascript short date pattern.
    /// </summary>
    /// <param name="dateTimeFormat">The date time format.</param>
    /// <returns></returns>
    public static string GetJavascriptShortDatePattern(DateTimeFormatInfo dateTimeFormat)
    {
        return dateTimeFormat.ShortDatePattern
            .Replace("M", "m")
            .Replace("yy", "y");
    }
}

Including Javascript in page:

    /// <summary>
    /// Inserts the localized datepicker jquery code
    /// </summary>
    private void InsertLocalizedDatepickerScript()
    {

        string dateformat = wxDateTimeConvert.GetJavascriptShortDatePattern(Thread.CurrentThread.CurrentUICulture.DateTimeFormat);
        String js = @"$(document).ready(function() {
$("".datepicker"").datepicker({
    changeYear: true,
    dateFormat: '" + dateformat + @"',
    maxDate: new Date()
  });
});";
        this.Page.Header.Controls.Add(
            new LiteralControl("<script type=\"text/javascript\">" + js + "</script>")
        );
    }

However, this does not handle month or day names, time formatting or other special cases.

like image 53
mattanja Avatar answered Oct 09 '22 11:10

mattanja