Jonas Stawski

Everything .NET and More

DateTime.ToString(string)

This is more of a "mental" note for me than anything else, but I would like to share it with everyone as well. The DateTime.ToString method has 2 overloads, one with no parameters and the other with a string parameter. I would like to talk about the second one (hence the title of this post). You can pass a custom format pattern as the parameter to show the date anyway you want. Here are some of the possible values:

Pattern Description Example
yyyy Full Year 2008
yy Year 08
MM Month 05
MMM Month May
dd Day 02
d Day 2
HH Hour Military Notation 21
h Hour 9
mm Minutes 59
ss Seconds 34
ffff Milliseconds 0589
zzz Zone -04:00
t Meridiem P
tt Full Meridiem PM

 

Of course you can combine any of these to form a pattern for example:

yyyyMMddHHmmssffff would yield something like 200805221122350587 and you would do so like this:

DateTime.Now.ToString("yyyyMMddHHmmssffff");

There are also some predefined patterns

Pattern Example
d 5/22/2008
D Thursday, May 22, 2008
f Thursday, May 22, 2008 11:22 AM
F Thursday, May 22, 2008 11:22:34 AM
g 5/22/2008 11:22 AM
G 5/22/2008 11:22:34 AM
m May 22
o 2008-05-22T11:22:34:04.0000000
R Thu, 22 May 2008 11:22:34 EST
s 2008-05-22T11:22:34
t 11:22 AM
T 11:22:34 AM
u 2008-05-22 11:22:04Z
U Thursday, May 22, 2008 11:22:34 AM
y May, 2008

Happy Programming!

Comments (1) -

Just a FYI - in fact DateTime.ToString has four overloads. In addition to the ones you mention, it also has one that takes a format provider, and one that takes both a string and a format provider.

If your code will always run under the same culture settings you don't need to use the format provider overloads but if your code has any chance of ending up on a system in another country (or being accessed from another country), and if it in any way relies on parsing or formatting dates to a specific format you may want to take a look at the format providers.

For example:
While "d" may produce "5/22/2008" on a US system, it will product 22/05/2008 on a UK (british) system, 2008-05-22 on a Swedish system, 22/5/2551 on a Thai system (where the current year is not 2008 but 2551), 22/5/29 on an arabic system (where it is currently year 1429) and so on.

The format provider overloads exist to ensure consistent formatting and parsing when/if multiple cultures may be involved; it allows you to specify exactly what culture to use use in DateTime.ToString and DateTime.Parse:

DateTime.Now.ToString("dd MMM yyyy", new System.Globalization.CultureInfo("en-us").DateTimeFormat)

Reply

Add comment

biuquote
Loading