Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

You can set the default culture at the web.config (application level), Page directive or control directive.

I have various apps where the master pages are set up for different cultures, and the pages and controls inherit from there.

You can manipulate the short date format by changing the setting in the regional settings in the control panel on your server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top