Home >Backend Development >C++ >How to Format Dates in C#?

How to Format Dates in C#?

DDD
DDDOriginal
2024-10-29 02:39:02503browse

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:

  • [DateTime.ToString() Method](https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring)
  • [Standard Date and Time Format Strings](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings)
  • [Custom Date and Time Format Strings](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn