Use custom date and time formats in C#

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 Make a program generate HTML table code for ListView data and display it in a WebBrowser control in C# to convert the results into the following HTML table.

Date Formats
Name Format Result
Day of month (1 - 31) d 15
Day of month (01 - 31) dd 15
Abbreviated day of week ddd Mon
Full day of week dddd Mon
Month (1 - 12) M 3
Month (01 - 12) MM 03
Month abbreviation MMM Mar
Month name MMMM March
Year (0 - 99) y 10
Year (01 - 99) yy 10
Year (minimum 3 digits) yyy 2010
Year (4 digits) yyyy 2010
Year (5 digits) yyyyy 02010
Era g A.D.
Era gg A.D.
Date separator / /
Time Formats
Name Format Result
Hour (1 - 12) h 6
Hour (01 - 12) hh 06
Hour (1 - 23) H 18
Hour (01 - 23) HH 18
Minute (0 - 59) m 37
Minute (00 - 59) mm 37
Second (0 - 59) s 12
Second (00 - 59) ss 12
Tenths of seconds f 1
Hundredths of seconds ff 15
Milliseconds fff 157
Ten thousandths of seconds ffff 1570
Hundred thousandths of seconds fffff 15700
Millionths of seconds ffffff 157000
Ten millionths of seconds fffffff 1570000
A/P t P
AM/PM tt PM
If non-zero, tenths of seconds F 1
If non-zero, hundredths of seconds FF 15
If non-zero, milliseconds FFF 157
If non-zero, ten thousandths of seconds FFFF 157
If non-zero, hundred thousandths of seconds FFFFF 157
If non-zero, millionths of seconds FFFFFF 157
If non-zero, ten millionths of seconds FFFFFFF 157
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.

See also:

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.