C# Custom Datetime Format String

Many Date times format patterns are available in c# asp.net, you can use them and get custom format as you required, DateTime Type have the method ToString that can be use to get custom datetime format just pass the string format.

Below is the many letter format provided by Datetime type ToString Method and expected result given in small bracket definition is given in bold string after equal. 

Day

d , dd = Day (1, 01)
ddd , dddd = Day of week (Mon, Monday)

Month

M , MM = Month (2 , 02)
MMM , MMMM = Month Name Of The Year (Jan, January)

Year

y , yy = Year (13, 13)
yyy , yyyy = Year (2013, 2013)

Hours

h, hh = 12 Hours (2, 02)

24 Hours Format

H , HH = 24 Hour (2, 02)

Minutes and Seconds

m , mm = Minute (6, 06)
s, ss = Second (3, 03)

Time Type

t = A.M, P.M (A, P)
tt = A.M, P.M (AM, PM) 

About Single and double letter

dd , MM, yy, hh, HH, mm, ss = Display leading Zero
d , M, y, h, H, m, s = Do not display leading Zero

Example is given below, code and its output (in front of the code)

DateTime.Now.ToString("MM/dd/yyyy"); //04/13/2013
DateTime.Now.ToString("M/d/yyyy");   //4/13/201
DateTime.Now.ToString("ddd MMM yyyy"); //Sat Apr 2013
DateTime.Now.ToString("dddd - MMMM - yyyy"); //Saturday - April - 2013

DateTime.Now.ToString("dddd MMMM yyyy  hh:mm:ss tt"); //Saturday April 2013 03:07:29 PM

24 Hours Format :
DateTime.Now.ToString("dddd HH:mm:ss"); //Saturday 15:27:51


Here is the some predefined Single-letter datetime format provided by asp.net.

DateTime.Now.ToString("F"); //Saturday, April 13, 2013 3:16:54 PM
DateTime.Now.ToString("f"); //Saturday, April 13, 2013 3:13 PM
DateTime.Now.ToString("G"); //4/13/2013 3:16:19 PM
DateTime.Now.ToString("s");  //2013-04-13T15:19:22
DateTime.Now.ToString("u"); //2013-04-13 15:23:46Z
DateTime.Now.ToString("g"); //4/13/2013 3:15 PM

DateTime.Now.ToString("D"); //Saturday, April 13, 2013
DateTime.Now.ToString("d"); //4/13/2013
DateTime.Now.ToString("M"); //April 13
DateTime.Now.ToString("m"); //April 13
DateTime.Now.ToString("Y"); //April 13
DateTime.Now.ToString("y"); //April 13

DateTime.Now.ToString("t"); //3:20 PM
DateTime.Now.ToString("T"); //3:20:46 PM


Recent Article