Home >Backend Development >C++ >How do I format a date in C#?
Format Date in C#
The question revolves around formatting a date in a specific format, such as "dd/mm/yyyy" or "mm/dd/yy". The C# equivalent to VB's format method is the ToString() method of the DateTime class.
To format a date, simply call the ToString() method with the desired format string:
<code class="csharp">DateTime.Now.ToString("dd/MM/yy"); // Returns "02/01/09"</code>
You can also use one of the predefined date/time format strings:
<code class="csharp">DateTime.Now.ToString("g"); // Returns "2/1/09 9:07 PM" in en-US</code>
For more control over the formatting, you can use custom formatting strings. This lets you specify the exact format you want, including specific delimiters and placeholders.
Additional Considerations
If you need to display a date in a specific locale or culture, you can use the ToString() method that takes an IFormatProvider. This allows you to specify the culture to use for formatting:
<code class="csharp">DateTime dt = GetDate(); dt.ToString("g", new CultureInfo("en-US")); // Returns "5/26/09 10:39 PM" dt.ToString("g", new CultureInfo("de-CH")); // Returns "26.05.09 22:39"</code>
Alternatively, you can set the CurrentCulture of the current thread to the desired culture before formatting the date:
<code class="csharp">Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); dt.ToString("g"); // Returns "5/26/09 10:39 PM"</code>
The above is the detailed content of How do I format a date in C#?. For more information, please follow other related articles on the PHP Chinese website!