Home  >  Article  >  Backend Development  >  How Can I Format Dates in C# Similar to VB.NET\'s `format()` Function?

How Can I Format Dates in C# Similar to VB.NET\'s `format()` Function?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 02:20:02322browse

How Can I Format Dates in C# Similar to VB.NET's `format()` Function?

Formatting Dates in C#

In VB.NET, formatting dates is achieved using the format() function with the desired format strings, such as "dd/mm/yy". How can we achieve similar formatting in C#?

C# Implementation

C# offers a parallel solution through the DateTime.ToString() method:

<code class="c#">DateTime.Now.ToString("dd/MM/yy"); // dd/mm/yy format</code>

This method allows for customization of date formatting using format strings. For instance, to format a date in the "mm/dd/yy" format:

<code class="c#">DateTime.Now.ToString("MM/dd/yy"); // mm/dd/yy format</code>

Predefined Formats

For convenience, C# provides predefined date/time formats:

<code class="c#">DateTime.Now.ToString("g"); // "02/01/2009 9:07 PM" for en-US, "01.02.2009 21:07" for de-CH</code>

These ensure locale-independent formatting.

Locale-Specific Formatting

To format dates based on specific locales, use the CultureInfo class:

<code class="c#">DateTime dt = GetDate();
dt.ToString("g", new CultureInfo("en-US")); // "5/26/2009 10:39 PM" in en-US</code>

Alternatively, you can set the thread's CultureInfo:

<code class="c#">Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
dt.ToString("g"); // "5/26/2009 10:39 PM" in en-US</code>

By utilizing the ToString() method and its formatting options, you can effectively format dates in C#, whether in custom, predefined, or locale-specific formats.

The above is the detailed content of How Can I Format Dates in C# Similar to VB.NET\'s `format()` Function?. 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