Home >Backend Development >C++ >How to Format Dates in C#?
Formatting Dates in C#
When formatting a date as "dd/mm/yyyy" or "mm/dd/yy" in C#, utilize the DateTime.ToString() method.
For instance, to format the current date as "dd/MM/yy":
DateTime.Now.ToString("dd/MM/yy");
To format a specific date with the format "mm/dd/yy":
DateTime dt = GetDate(); dt.ToString("mm/dd/yy");
For additional flexibility, use predefined date/time formats:
DateTime.Now.ToString("g");
This ensures the correct format, regardless of the locale settings.
To display a date in a specific locale, utilize the overloaded ToString() method that accepts an IFormatProvider:
DateTime dt = GetDate(); dt.ToString("g", new CultureInfo("en-US")); // "5/26/2009 10:39 PM" dt.ToString("g", new CultureInfo("de-CH")); // "26.05.2009 22:39"
Alternatively, set the current thread's CultureInfo before formatting:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); dt.ToString("g"); // "5/26/2009 10:39 PM" Thread.CurrentThread.CurrentCulture = new CultureInfo("de-CH"); dt.ToString("g"); // "26.05.2009 22:39"
For further information, refer to the following MSDN pages:
The above is the detailed content of How to Format Dates in C#?. For more information, please follow other related articles on the PHP Chinese website!