Home > Backend Development > C++ > 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
Release: 2024-11-01 02:20:02
Original
392 people have browsed it

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

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

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

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

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

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!

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