What the DateTime ToString() Methods Return

If your Windows is set to the USA style of date display, time, currency and numbers, the methods below will return the following:
ToLongDateString(): Friday, July 27, 2012
ToLongTimeString(): 9:26:49 AM
ToShortDateString(): 7/27/2012
ToShortTimeString(): 9:26 AM
ToString(): 7/27/2012 9:26:49 AM

If it is set to Czech / Czech Republic, you get this instead (the time gap is longer here because I had to restart the PC):

ToLongDateString(): 27. července 2012
ToLongTimeString(): 9:46:17
ToShortDateString(): 27.7.2012
ToShortTimeString(): 9:46
ToString(): 27.7.2012 9:46:17

You can also use the ToString() method to display the date differently from the Windows settings. Specifically like this (if you don’t know the language code, take a look at, for example, 👻 The tutorial on sharpertutorials.com is gone for good.):

C#
dateTime.ToString(CultureInfo.GetCultureInfoByIetfLanguageTag("en-us"));

If you want to display the date in any format you like, there is no need to piece it together like this:

C#
public static string UsaDateTimeToString(DateTime d)
{
    return d.Month + "/" + d.Day + "/" + d.Year + " " + d.Hour + ":" + d.Minute + ":" + d.Second;// +":" + miliseconds;
}

Simply call the method like this:

C#
dateTime.ToString("MM/dd/yyyy hh:mm:ss");

If you pass both parameters to the ToString method, the string parameter wins over IFormatProvider:

C#
dateTime.ToString("MM/dd/yyyy hh:mm:ss", CultureInfo.GetCultureInfoByIetfLanguageTag("cs-cz");

Categories

Leave a Reply