String format for DateTime in C#


Format DateTime using String.Format method.

Let us see an example −

Example

using System;

static class Demo {
   static void Main() {
      DateTime d = new DateTime(2018, 2, 8, 12, 7, 7, 123);

      Console.WriteLine(String.Format("{0:y yy yyy yyyy}", d));
      Console.WriteLine(String.Format("{0:M MM MMM MMMM}", d));
      Console.WriteLine(String.Format("{0:d dd ddd dddd}", d));
   }
}

Above we have first set the DateTime class object −

DateTime d = new DateTime(2018, 2, 8, 12, 7, 7, 123);

To format, we have used the String.Format() method and displayed date in different formats.

String.Format("{0:y yy yyy yyyy}", d)
String.Format("{0:M MM MMM MMMM}", d)
String.Format("{0:d dd ddd dddd}", d

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements