Home > Backend Development > C++ > body text

How do I format a date in C#?

Susan Sarandon
Release: 2024-10-30 02:32:02
Original
965 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!