Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Saturday, September 02, 2006

Formatting Dates in .NET

I am forgetful regarding the formatting of dates in .NET.  For example, I will try to put in something like "MM/DD/YYYY" and will get out something like "06/MM/YYYY."  As my head slaps my forehead on this issue, I then remember that string formatting is case sensitive and I need to use something like "MM/dd/yyyy" to get my desired result.  Check here for the common string formatting expressionsThanks to Steve Tibbett for this info.  Steve has some other good formatting info in his article on his blog.  I have gone ahead and copied over the date formats for my reference (not trying to steal info).

SpecifierTypeExample (Passed System.DateTime.Now)
dShort date10/12/2002
DLong dateDecember 10, 2002
tShort time10:11 PM
TLong time10:11:29 PM
fFull date & time December 10, 2002 10:11 PM
FFull date & time (long)December 10, 2002 10:11:29 PM
gDefault date & time10/12/2002 10:11 PM
GDefault date & time (long)10/12/2002 10:11:29 PM
MMonth day patternDecember 10
rRFC1123 date stringTue, 10 Dec 2002 22:11:29 GMT
sSortable date string2002-12-10T22:11:29
uUniversal sortable, local time2002-12-10 22:13:50Z
UUniversal sortable, GMTDecember 11, 2002 3:13:50 AM
YYear month patternDecember, 2002

The ‘U’ specifier seems broken; that string certainly isn’t sortable.

Custom date formatting:

SpecifierTypeExample Example Output
dddDay name{0:ddd}Tue
ddddFull day name{0:dddd}Tuesday
f, ff, …Second fractions{0:fff}932
gg, …Era{0:gg}A.D.
hh2 digit hour{0:hh}10
HH2 digit hour, 24hr format{0:HH}22
mmMinute 00-59{0:mm}38
MMMonth 01-12{0:MM}12
MMMMonth abbreviation{0:MMM}Dec
MMMMFull month name{0:MMMM}December
ssSeconds 00-59{0:ss}46
ttAM or PM{0:tt}PM
yyYear, 2 digits{0:yy}02
zzTimezone offset, 2 digits{0:zz}-05
zzzFull timezone offset{0:zzz}-05:00

Post a Comment