Format DateTime with standard date and time format strings in CSharp

Description

The following code shows how to format DateTime with standard date and time format strings.

Example


using System;// w ww  .j av  a2  s.c o  m

public class DateToStringExample
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2014, 6, 15, 21, 15, 07);

      string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", 
                               "R", "s", "t", "T", "u", "U", "y"};

      foreach (string standardFmt in standardFmts)
         Console.WriteLine("{0}: {1}", standardFmt, 
                           dateValue.ToString(standardFmt));



      string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", 
                             "dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" };

      foreach (string customFmt in customFmts)
         Console.WriteLine("'{0}': {1}", customFmt,dateValue.ToString(customFmt));
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var