Wednesday, 28 September 2011

Custom Date Formatting in C#


Every object has a method called ToString that returns a string representation of the object. The ToString method can accept a string parameter, which tells the object how to format itself – in the String.Format call, the formatting string is passed after the position, for example, “{0:##}”.
The text inside the curly braces is {index[,alignment][:formatString]}. If alignment is positive, the text is right-aligned in a field the given number of spaces; if it’s negative, it’s left-aligned.

Specifier
Type
Example
Example Output
dd
Day
{0:dd}
10
ddd
Day name
{0:ddd}
Tue
dddd
Full day name
{0:dddd}
Tuesday
f, ff, …
Second fractions
{0:fff}
932
gg, …
Era
{0:gg}
A.D.
hh
2 digit hour
{0:hh}
10
HH
2 digit hour, 24hr format
{0:HH}
22
mm
Minute 00-59
{0:mm}
38
MM
Month 01-12
{0:MM}
12
MMM
Month abbreviation
{0:MMM}
Dec
MMMM
Full month name
{0:MMMM}
December
ss
Seconds 00-59
{0:ss}
46
tt
AM or PM
{0:tt}
PM
yy
Year, 2 digits
{0:yy}
2
yyyy
Year
{0:yyyy}
2002
zz
Timezone offset, 2 digits
{0:zz}
-5
zzz
Full timezone offset
{0:zzz}
-05:00
:
Separator
{0:hh:mm:ss}
10:43:20
/
Separator
{0:dd/MM/yyyy}
10/12/2002

 

Ex:
string.Format("{0:yyyy-MM-dd}", DateTime.Today.Date)
Output:
2011-09-28

No comments:

Post a Comment