Home Programs How to Display the Date in Various Formats in C#

How to Display the Date in Various Formats in C#

In this article we look at a program that will display the date and time in various formats

The format parameter can contain either a single format specifier character  or a custom format pattern .

If format is null or an empty string (“”), the standard format specifier, “G”, is used.

// g Format Specifier de-DE Culture 31.10.2008 17:04 
// g Format Specifier en-US Culture 10/31/2008 5:04 PM
// g Format Specifier es-ES Culture 31/10/2008 17:04 
// g Format Specifier fr-FR Culture 31/10/2008 17:04

Example

The local time is calculated using TimeZone() function.

The TimeZone() function is used to convert a time from one time zone to another.

Then we use the DateTime.ToLocalTime() method to convert the value of the current DateTime object to the local time.

You can then use formatting

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeZone zone = TimeZone.CurrentTimeZone;
            DateTime date = zone.ToLocalTime(DateTime.Now);
            Console.WriteLine("Some Date Formats : ");
            Console.WriteLine("Date and Time:  {0}", date);
            Console.WriteLine(date.ToString("yyyy-MM-dd"));
            Console.WriteLine(date.ToString("dd-MMM-yy"));
            Console.WriteLine(date.ToString("M/d/yyyy"));
            Console.WriteLine(date.ToString("M/d/yy"));
            Console.WriteLine(date.ToString("MM/dd/yyyy"));
            Console.WriteLine(date.ToString("MM/dd/yy"));
            Console.WriteLine(date.ToString("yy/MM/dd"));
            Console.Read();
        }
    }
}

This will display something like the following

Some Date Formats :
Date and Time: 12/04/2022 18:18:10
2022-04-12
12-Apr-22
4/12/2022
4/12/22
04/12/2022
04/12/22
22/04/12

You may also like