String format for DateTime in C#

CsharpProgrammingServer Side Programming

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
raja
Published on 14-Aug-2018 12:53:25
Advertisements