Use custom date and time formats in C#

custom date and time formats

Note that custom date and time formats may not produce the result you want when you program runs in different locales. For example, the date January 23, 2010 should be displayed as 1/23/2010 in the United States but in as 23/1/2010 in England. If your code uses custom date and time formats, users may see a format they don’t expect. To avoid this sort of problem, use the standard date and time formats whenever possible.

You can use numeric formatting characters to display date and time values in particular formats. These formats work with a variable’s ToString method as well as with String.Format. For example, the code DateTime.Now.ToString("M/dd/yyyy") returns the current date in the format 1/23/2010.

This example builds a ListView that demonstrates the various custom date and time formats. It then uses code from the example Use ListView data to generate HTML TABLE code in C# to convert the results into the following HTML table.

Date Formats
Name Format Result
Day of month (1 – 31) d 18
Day of month (01 – 31) dd 18
Abbreviated day of week ddd Mon
Full day of week dddd Mon
Month (1 – 12) M 8
Month (01 – 12) MM 08
Month abbreviation MMM Aug
Month name MMMM August
Year (0 – 99) y 14
Year (01 – 99) yy 14
Year (minimum 3 digits) yyy 2014
Year (4 digits) yyyy 2014
Year (5 digits) yyyyy 02014
Era g A.D.
Era gg A.D.
Date separator / /
Time Formats
Name Format Result
Hour (1 – 12) h 5
Hour (01 – 12) hh 05
Hour (1 – 23) H 17
Hour (01 – 23) HH 17
Minute (0 – 59) m 19
Minute (00 – 59) mm 19
Second (0 – 59) s 16
Second (00 – 59) ss 16
Tenths of seconds f 6
Hundredths of seconds ff 66
Milliseconds fff 661
Ten thousandths of seconds ffff 6611
Hundred thousandths of seconds fffff 66111
Millionths of seconds ffffff 661115
Ten millionths of seconds fffffff 6611157
A/P t P
If non-zero, tenths of seconds F 6
If non-zero, hundredths of seconds FF 66
If non-zero, milliseconds FFF 661
If non-zero, ten thousandths of seconds FFFF 6611
If non-zero, hundred thousandths of seconds FFFFF 66111
If non-zero, millionths of seconds FFFFFF 661115
If non-zero, ten millionths of seconds FFFFFFF 6611157
UTC hour offset z -6
UTC hour offset with leading 0 zz -06
UTC hour and minute offset zzz -06:00
Time separator : :

Note that some of the formats only work properly when embedded in a longer format string. For example, “M” by itself returns a month plus year format as in “March 15” (on my system). If you add a % before the character (as in “%M”), then the character works properly.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in formatting, strings and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.