Monday, August 15, 2016

DateTime Formatting in C#

In C#, we can do custom formatting of DateTime apart from standard
Date and Time Formats.

Formatting can be done using DateTime.ToString method and also by String.Format
method.

Here I will explain commonly used examples.

Some commonly used Format Specifiers are the following

.............................................................................................

d    -  represents day from 1 to 31

dd  -  represents day in two digits from 01 to 31

ddd - represents abbreviated name of the day of the week

dddd - represents full name of the day of the week

h - represents hour from 1 to 12 using 12 hour clock

hh - represents hour in two digits from 01 to 12 using 12 hour clock

H  - represents hour from 0 to 23 using 24 hour clock

HH - represents hour in two digits from 00 to 23 using 24 hour clock

m - represents minute from 0 to 59

mm - represents minute in two digits from 00 to 59

M - represents month from 1 to 12

MM - represents month in two digits from 01 to 12

MMM - represents abbreviated name of the month

MMMM - represents full name of the month

s - represents second from 0 to 59

ss - represents second in two digits from 00 to 59

tt - represents AM/PM

y - represents year from 0 to 99

yy - represents year in two digits from 00 to 99

yyy - represents year with a minimum of 3 digits

yyyy - represents year in 4 digit

:  Time separator 

/  Date separator

..............................................................................................

Below are some examples using ToString method :

string str = DateTime.Now.ToString("MM/dd/yyyy");

Output is : 08/15/2016

string str = DateTime.Now.ToString("dd/MM/yyyy");

Output is : 15/08/2016

string str = DateTime.Now.ToString("dd MMM,yyyy");

Output is : 15 Aug,2016

string str = DateTime.Now.ToString("dd MMMM,yyyy");

Output is : 15 August,2016

string str = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

Output is : 15/08/2016 15:44:38

string str = DateTime.Now.ToString("dd/MM/yyyy hh:mm tt");

Output is : 15/08/2016 03:44 PM

We can do formatting using String.Format as follows "

DateTime dt = new DateTime();
dt = DateTime.Now;
string str=String.Format("{0:dd MMM,yyyy hh:mm tt}", dt);

Output is : 15 August,2016 03:44 PM

DateTime dt = new DateTime();
dt = DateTime.Now;
string str=String.Format("{0:dddd dd MMM,yyyy hh:mm tt}", dt);

Output is : Monday 15 August,2016 03:44 PM

Note :  Regional and Language options settings in ControlPanel influence the result
of formatting


No comments:

Post a Comment