Author : Guest
Total Views : 457
Posted On : Sun, Mar 18, 2018
Updated On : Mon, Mar 19, 2018

String Format for DateTime

In this example, you will learn that how you can use String.Format method to format the DateTime in various ways.

Custom format specifiers

Custom formate specifiers are used inside String.Format function to retrieve different parts of DateTime. Following is the list of custom format specifiers and there uses.

Specifier Name Represents
y year
M Month
d Day
h Hour (12 hours)
H Hour (24 hours)
m Minute
s Second
f Fraction Second
F Fraction Second (Removes trailing zeros)
t PM or AM
z Time Zone

Example

Let's understand format specifiers using an example :

DateTime dt = new DateTime(2018, 3, 18, 04, 7, 30, 454);
Console.WriteLine(String.Format("{0:y yy yyy yyyy}", dt));            // "18 18 2018 2018"   year
Console.WriteLine(String.Format("{0:M MM MMM MMMM}", dt));            // "3 03 Mar March"  month
Console.WriteLine(String.Format("{0:d dd ddd dddd}", dt));            // "18 18 Sun Sunday" day
Console.WriteLine(String.Format("{0:h hh H HH}", dt));                // 4 04 4 04"      hour 12/24
Console.WriteLine(String.Format("{0:m mm}", dt));                     // "7 07"            minute
Console.WriteLine(String.Format("{0:s ss}", dt));                     // "30 30"            second
Console.WriteLine(String.Format("{0:f ff fff ffff}", dt));            // "4 45 454 4540"   sec.fraction
Console.WriteLine(String.Format("{0:F FF FFF FFFF}", dt));            // "4 45 454 454"    without zeroes
Console.WriteLine(String.Format("{0:t tt}", dt));                     // "A AM"            A.M. or P.M.
Console.WriteLine(String.Format("{0:z zz zzz}", dt));                 // "+5 +05 +05:30"   time zone

Output

Following is the output of above lines.

Output

18 18 2018 2018
3 03 Mar March
18 18 Sun Sunday
4 04 4 04
7 07
30 30
4 45 454 4540
4 45 454 454
A AM
+5 +05 +05:30

Standard DateTime Formatting

In the above example, you have seen that how you can achieve the desired format of DateTime using different format specifiers. However .Net framework already has a class DateTimeFormatInfo which contains different properties to format the DateTime. Following is the list of properties and the corresponding format specifiers they use.

DateTimeFormatInfo property Specifier Pattern value (for en-US culture)
ShortTimePattern t h:mm tt
ShortDatePattern d M/d/yyyy
LongTimePattern T h:mm:ss tt
LongDatePattern D dddd, MMMM dd, yyyy
(combination of D and t)
FullDateTimePattern
f
F
dddd, MMMM dd, yyyy h:mm tt
dddd, MMMM dd, yyyy h:mm:ss tt
MonthDayPattern m,M MMMM dd
YearMonthPattern y, Y MMMM, yyyy
RFC1123Pattern r, R ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
SortableDateTi­mePattern s yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
UniversalSorta­bleDateTimePat­tern u yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)

Thanks