Search code examples
asp.netlocalizationcalendarextender

How to override AjaxToolkit CalendarExtender date to string conversion?


i am using the Microsoft Ajax Toolkit CalendarExtender control, to add calendar drop-down functionality to a regular TextBox:

<asp:TextBox ID="edStartDate" runat="server" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" 
      TargetControlID="edStartDate" />

Which works fine for most client locales. It seems that the control does a server-request in order to convert a DateTime into a localized String.

For example, today (October 1st, 2012) displays fine in Arabic 15/11/33:

enter image description here

And also displays fine in Lower Sorbian 1. 10. 2012:

enter image description here


But some locales do not display properly in .NET 1////10////2012:

enter image description here

In this case i need some sort of OnFormatDate event, that i can supply the correct localization of a date to a string. Which leads to my question:

How to override AjaxToolkit CalendarExtender date to string conversion?


Note: Don't confuse the question with the example.

  • i'm asking how to customize the conversion of a date to a string in a CalendarExtender
  • even if i'm not dealing with a bug in .NET, it doesn't change my question
  • even if i'm not dealing with a CalendarExtender, i'm still asking the question

Solution

  • i used the same solution i used in a native Win32 application.

    The CalendarExtender uses the "Short date" format (d). The fix is to work around the bug in .NET:

    String format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
    
    format = FixDotNetDateTimeFormatStringsBug(format);
    
    CalendarExtender1.Format = format; //starts as "d", the "Short date" format
    

    with our helper-fixer:

    public String FixDotNetDateTimeFormatStringBug(String format)
    {
       //The bug in .NET is that it assumes "/" in a date pattern means "the date separator".
       //What .NET doesn't realize is that the locale strings returned by Windows
       // are the *Windows* format strings. 
       //The bug is exposed in locale's that use two slashes as for their date separator:
       //      dd//MM//yyyy
       //Which .NET misinterprets to give:
       //      30////11////2011
       //when really it should be taken literally to be:
       //      dd'//'MM'//'yyyy
       //which is what this fix does:
    
       return = format.Replace("/", "'/'");
    }
    

    Or, if you like more concisely:

    CalendarExtender1.Format = FixDotNetDateTimeFormatStringsBug(
          CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern);
    

    Note: Any code is released into the public domain. No attribution required.