This example will help you know how to use the datetime format in c#. You can use the ToString method with DateTime class to custom format date and time.

using System;

namespace CSharpCode
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt = DateTime.Now;
            Console.WriteLine("{0}", dt);
            Console.WriteLine("{0:M/d/yyyy}", dt);
            Console.WriteLine("{0:MM/dd/yyyy}", dt);
            Console.WriteLine("{0 dd ddd dddd}", dt);
            Console.WriteLine("{0/M/yyyy HH:mm:ss}", dt);
            Console.WriteLine("{0:h hh H HH}", dt);
            Console.WriteLine("{0:M MM MMM MMMM}", dt);
            Console.WriteLine("{0:m mm}", dt);
            Console.WriteLine("{0dd, MMM d, yyyy}", dt);
            Console.WriteLine("{0:s ss}", dt);
            Console.WriteLine("{0:MM/dd/yy}", dt);
            Console.WriteLine("{0ddd, MMMM d, yyyy}", dt);
            Console.WriteLine("{0:MM/dd/yyyy}", dt);
            Console.ReadLine();
        }
    }
}

The above example will get the current datetime, then use pattern format to format our datetime. As you can see you can use the slash to format date and the colon to format time.

Console.WriteLine("{0/M/yyyy HH:mm:ss}", dt);

c# datetime format

Note

  • y: year
  • M: month
  • d: day
  • h: 12 hour
  • H: 24 hour
  • m: minute
  • s: second
  • f: second fraction
  • t: AM or PM
  • z: time zone