Search code examples
c#datetimeasp.net-3.5string-formattingcultureinfo

Change ASP.NET default Culture for date formatting


For some reason, ASP.NET code on my server is now returning a format of dd/MM/yyyy instead of MM/dd/yyyy when I use DateTime.ToString("g").

Rather than replacing all the "g" format strings with a concrete format string or CultureInfo argument, is there a way I can just override, across the application, the default "short date" format?

My preference is actually "yyyy-MM-dd" as the default format, but I can live with the US-centric MM/dd/yyyy, as all users are in the US.

Clarification: I do not want to change the entire default culture, which could impact things such as currency and use of decimals/commas in formatting numbers.

I just want to override any ToString("g") call to use the ISO/IEC 8824 date format ("yyyy-MM-dd").

I could search and replace across my code to force a CultureInfo in every ToString() call, but that doesn't strike me as the most maintainable solution.

My current solution is that I've defined a static method for formatting a date, and I call it instead of ToString() across my entire codebase. But again, if I forget to do so somewhere in the code, I'll have a goofy date again.


Solution

  • Setting the culture wasn't an option, nor was depending on the server's regional settings.

    I ended up writing a utility function for formatting dates:

    Public Shared Function FormatShortDate(ByVal d As Date) As String
        If d=#1/1/0001# Then Return ""
        If d=#1/1/1900# Then Return ""
        'ISO/IEC 8824 date format
        Return d.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
    End Function
    

    I call this everywhere I need to push a date out to the user. It also handles display of default ("magic") dates.

    I wrote some similar functions for and FormatShortDateTime and FormatLongDateTime.