Welcome to MSDN Blogs Sign in | Join | Help

Kathy Kam

Reflection on the CLR and .NET
.NET Format String 102: DateTime Format String

"I see stuff like "zz" passed into DateTime.ToString(). What exactly does that do?" -- Very Confused DateTime String Formatter

DateTime has its own set format string modifiers because there are so many ways to display a date and time. There are 2 things that affects how your DateTime is formatted.

1. CultureInfo

Besides the format string modifiers, CultureInfo on your thread also greatly influences the output. My examples will be based on CultureInfo.InvariantCulture.

You can set the CultureInfo on your thread by calling this

Thread
.CurrentThread.CurrentCulture = <some culture>;
eg.
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

2. Format String

There are actually two different ways of formatting a DateTime object. Both methods produce the same results:

DateTime now = DateTime.Now;

now.ToString("<dateTimeFormatString>");

String.Format("<strFormat>", now);

 

Basically:

<strFormat> = {<argument index>:<dateTimeFormatString>}

My examples will use the DateTime.ToString() method.

If you have read any DateTime format string documentation, you will know that the .NET platform has two different styles of DateTime format string:

2-a. Standard Format String

This is basically built in short hand for custom format string. You pass in the one character string to denote which custom format you want.

i.e.
now.ToString("d");  // "09/27/2006"
now.ToString("D");  // "Tuesday, 27 September 2006"
now.ToString("G");  // "09/27/2006 14:15:39"

All of the format string syntax I discussed in ".NET Format String 101" is invalid here. Also, if you call now.ToString(), it is basically calling now.ToString("G");

I have included my own table mapping Standard Format String to Custom Format string in part 2-c below. MSDN actually has a pretty good table that describe what each item does, and DateTime.ToString() has a pretty good code example that shows what each format string specifier do. Also if you just want samples, MSDN has a "Standard Date Time Format String Output example" here. Because documentation is so good. I won't go into this too much. :)

2-b. Custom Format String

Custom format string gives you the flexibility to build your own formatting. When using a single character format string specifier, you will need to prepend it with a "%", otherwise it will be interpreted as a Standard Format String. Here are the basics for building your own string:

DateTime now = new DateTime(2006, 9, 07, 15, 06, 01, 08, DateTimeKind.Local);

now.ToString();      //"09/27/2006 15:06:01"

 

Year

now.ToString("%y");   //"6"

now.ToString("yy");   //"06"

now.ToString("yyy");  //"2006"

now.ToString("yyyy"); //"2006"

 

Month

now.ToString("%M");    //"9"

now.ToString("MM");    //"09"

now.ToString("MMM");   //"Sep"

now.ToString("MMMM");  //"September"

 

Day

now.ToString("%d");    //"7"

now.ToString("dd");    //"07"

now.ToString("ddd");   //"Thu"

now.ToString("dddd");  //"Thursday"

 

Hour

now.ToString("%h");    //"3"

now.ToString("hh");    //"03"

now.ToString("hhh");   //"03"

now.ToString("hhhh");  //"03"

now.ToString("%H");    //"15"

now.ToString("HH");    //"15"

now.ToString("HHH");   //"15"

now.ToString("HHHH");  //"15"

 

Minutes

now.ToString("%m");    //"3"

now.ToString("mm");    //"03"

now.ToString("mmm");   //"03"

now.ToString("mmmm");  //"03"

 

Seconds

now.ToString("%s");    //"1"

now.ToString("ss");    //"01"

now.ToString("sss");   //"01"

now.ToString("ssss");  //"01"

 

Milliseconds

now.ToString("%f");    //"0"

now.ToString("ff");    //"00"

now.ToString("fff");   //"008"

now.ToString("ffff");  //"0080"

now.ToString("%F");    //""

now.ToString("FF");    //""

now.ToString("FFF");   //"008"

now.ToString("FFFF");  //"008"

 

Kind

now.ToString("%K");    //"-07:00"

now.ToString("KK");    //"-07:00-07:00"

now.ToString("KKK");   //"-07:00-07:00-07:00"

now.ToString("KKKK");  //"-07:00-07:00-07:00-07:00"

// Note: The multiple K were just read as multiple instances of the

// single K

 

DateTime unspecified = new DateTime(now.Ticks, DateTimeKind.Unspecified);

unspecified.ToString("%K");   //""

 

DateTime utc = new DateTime(now.Ticks, DateTimeKind.Utc);

utc.ToString("%K");           //"Z"

 

TimeZone

now.ToString("%z");     //"-7"

now.ToString("zz");     //"-07"

now.ToString("zzz");    //"-07:00"

now.ToString("zzzz");   //"-07:00"

 

Other

now.ToString("%g");    //"A.D."

now.ToString("gg");    //"A.D."

now.ToString("ggg");   //"A.D."

now.ToString("gggg");  //"A.D."

 

now.ToString("%t");    //"P"

now.ToString("tt");    //"PM"

now.ToString("ttt");   //"PM"

now.ToString("tttt");  //"PM" 

2-c. Additional Resources

Now that you understand what Standard and Custom format strings are, here is a table of Standard Format String to Custom Format String mapping:

Year Month Day Patterns:
d      = "MM/dd/yyyy"
D      = "dddd, dd MMMM yyyy"
M or m = "MMMM dd"
Y or y = "yyyy MMMM"

Time Patterns:
t      = "HH:mm"
T      = "HH:mm:ss"

Year Month Day and Time without Time Zones:
f      = "dddd, dd MMMM yyyy HH:mm"
F      = "dddd, dd MMMM yyyy HH:mm:ss"
g      = "MM/dd/yyyy HH:mm"
G      = "MM/dd/yyyy HH:mm:ss"

Year Month Day and Time with Time Zones:
o      = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"
R or r = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"
s      = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"
u      = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
U      = "dddd, dd MMMM yyyy HH:mm:ss"

All other single characters will throw an exception.

Answering the question...

So finally, to answer the question that began this whole discussion. "What exactly would "zz" do?"  i.e. What would "now.ToString("zz")" return?

Because there are 2 characters, it will be interpreted as a custom format string. "zz" stands for the signed time zone offset with a leading zero for single digit offsets. For me, being in Pacific Standard Time, my return value would be "-07". 

<Editorial Comment>
My most popular post was "
.NET Format String 101". The topic I have posted the most about is DateTime, Time Zone and so forth. It only seem fitting that I write a post about Format Strings in DateTime. I hope readers enjoy this post as much as my previous Format String post. :) I know MSDN actually covers this better than normal Format String, so I am not sure whether this is as valuable. What do you think? Are there any more "hot topics" that you are just dying for someone to explain?

Also, here are the MSDN resources:
- DateTime.ToString

Standard DateTime Format Strings 
- Standard Date Time Format String Output

- Custom DateTime Format Strings 
- Custom DateTime Format Strings Output Examples


</Editorial Comment>

 

Posted: Friday, September 29, 2006 8:00 AM by KathyKam

Comments

Peter Ritchie said:

Hi Kathy.  Blog entries on topics covered in MSDN are always welcomed!  It's always good to have multiple perspectives, don't let a topics coverage in MSDN sway you from blogging about it.

Thanks
# September 29, 2006 11:07 AM

Kris said:

Thank you. This is much better than reading the MSDN documentation. Conscise and right on target!

# September 29, 2006 12:49 PM

KathyKam said:

Hey Kris and Peter, Thanks for the feedback! :) Are there any topics you think is particularly poorly done in MSDN? Or are there any topics that are just not covered enough in MSDN? I am looking for something that EVERYONE uses like ... well... format strings. :) Cheers, Kathy
# September 29, 2006 1:01 PM

Richard said:

"%d" should return "7", not "07".

Also, the output for "H" and "h" is the wrong way round:
- "H" uses the 24-hour clock ("15");
- "h" uses the 12-hour clock ("3")
# September 29, 2006 8:42 PM

KathyKam said:

Hi Richard, Thanks for catching it! Thanks, Kathy
# September 29, 2006 9:18 PM

Jason Haley said:

# September 30, 2006 12:47 PM

Chris Love said:

Kathy this is a great peice of work.  I am always messing up with Date Formatting and this will be a great reverence page for me in the future.
# September 30, 2006 6:21 PM

Chris Love's Official Blog - Professional ASP.NET said:

I am always looking for good references on the net and one of the things I tend to have problems with is dealing for date formatting.  Katy Kam has a great entry on her blog which should serve as a great reference for Date formatting in .NET.
# September 30, 2006 6:24 PM

Depechie said:

Hey Kathy,

I've found out that the DateTime formatting rules are a bit awkward when you use them in an international setting.

When you change the regional settings, only the Long Date notation of .Net follow them... and not the Short Date notation !

Resulting in a weird output when you use DateTime.Now.ToString("t") !

Just check it, set the English (US) settings to show 24 hours notation and then perform DateTime.Now.ToString("t"), you will see this still gives the 12 hours notation and that is for a programmer a not expected result.

# October 17, 2006 3:57 AM

Rolf said:

How sad I have to get this info here and you see the need to publish it.

Microsoft.Blogs.SearchYourselfCrazy(anything)

.NET 4?

# November 27, 2006 2:48 PM

Muhammad Ali said:

I LOVE YOU KATHY ! .. .MSDN SIMPLIFIED! GREAT REFERENCE!

# December 23, 2006 6:51 AM

Kevin Isom's Blog said:

Kathy Kam : .NET Format String 102: DateTime Format StringFor those times when you can't remember what to add to get the A.D. after the year.

# May 22, 2007 8:38 PM

Joe Wood said:

Thanks Kathy, great post. Worth keeping this on file.

My only issue is that it's pity some of these custom formats aren't supported by the DateTimePicker - it must have its own formatting code!  

Maybe this could be fixed in the Acropolis DateTimePicker :)

# July 24, 2007 5:14 PM

Kennith Mann III said:

I've noticed that using "G" does not yield a 24 hour time, but instead a 12 hour (with AM/PM).

If it helps, C# .NET 2.0, Winforms, VS2005.

# October 23, 2007 9:37 AM

Rajesh said:

Nice article

I am getting date as "2001-03-01-09.41.08.000000". How to format this to a date. I have tried with DateTime.parse("2001-03-01-09.41.08.000000") but it is giving me error

Please Help me. I am stuck badly

# November 14, 2007 3:07 AM

farhan said:

Is there any way to get the format based on the current system datetime format??

Thanks

Farhan

farhan.ejaz@gmail.com

# November 19, 2007 9:54 AM

Prashanth said:

Ok thank you,

but i want that how can i compare the DataTime in a given format

thanks

Prashanth

# December 6, 2007 1:42 PM

jeevs said:

Thanks a lot after long search i get this thankyou Kathy!It helps me lot

# January 12, 2008 3:04 AM

Zafree said:

Kathy...how do i use the DateTime string to put in a name of a file when it is been uploaded by a user??

such as this:

The Date : 13 January 2008

The Time : 05.34.36 pm

The File That is going to be Uploaded : Jagged.doc

Therefore the file's name changes like this Jagged20080113173436.doc

something similar to this...how do i do it?

# January 14, 2008 4:34 AM

SA said:

# February 5, 2008 5:37 AM

Kathy Kam said:

There are a lot of blogs out that that tries to explain which is what, and why it is the way it is. To

# March 11, 2008 7:27 PM

Farrukh Rafique said:

Hi there,

I have made several attempts in several different ways / formats to save time in SQL Table field. In every case current date also get saved.

I hope u will bring out a solution of this problem of mine.

;)

# March 26, 2008 9:51 AM

Ramesh Sahoo said:

Conversion from string "22/04/2008" to type 'Date' is not valid

# April 22, 2008 8:31 AM

Pruthvi said:

DateTime.Now.ToString("G") does not give me 24 hour format. ??????

# May 23, 2008 4:43 PM

Neeraj P K said:

Hi...,

This was very helpful.

I was just searching for "2008-06-16 10:40:55 AM" format for date. After a long search I foud your article and saved a lot of time for me.

Thanks a lot...

# June 13, 2008 6:21 AM

Samruddhi said:

Nice post,

is there any way to format a date string

for eg.

(06/07/2008) into (6th July 2008)?

thanks in advance

# July 9, 2008 3:23 AM

Cynical Pirate Industries said:

Make your code less crazy - Format Strings

# July 10, 2008 10:12 PM

Chiru said:

Helpful and Nice post.Thank you Kathy

# July 30, 2008 11:43 AM

jiv said:

hi

Kathy thanks a lot & lot i found in ur article only.

this is very helpfull.

:) jiv

# August 8, 2008 10:08 AM

Mahesh said:

This was very helpful.

I was just searching for "2008-06-16 10:40:55 AM" format for date. After a long search I foud your article and saved a lot of time for me.

Thanks a lot...

# August 12, 2008 12:53 PM

CodeBork said:

.NET format strings rock. These are roughly equivalent to the old-school C-style sprintf() functions, with their %d, etc., symbols. There's some serious power to these strings, however; think PHP's date() function on acid, and for more than just dates

# August 21, 2008 2:00 PM

sampath said:

its really a very good help

Thank you.

# December 3, 2008 5:46 AM

Brad C said:

great breakdown on this topic, very helpful, thanks!

# December 10, 2008 2:45 PM

Rahat Ali said:

Kathy thanks a lot for suca a marvelous management in display this useful information. It is very handy.

# January 26, 2009 3:39 AM

B Prashanth said:

Finest explanation... Awesome. Thanks.

# January 29, 2009 8:55 AM

Tony, Switzerland said:

Thank you very much.

Without this valuable information I could not have solved my 24 hour-clock-problem.

# February 8, 2009 10:22 AM

David C, London said:

Thanks Kathy, very helpful posting. I like your style - very clear explanation with good examples - this being an area that is simple but hasn't ever been explained clearly for me before. Cheers David

# March 8, 2009 5:30 AM

How to find no. of Months B/W two dates said:

How to find no. of Months B/W two dates?

# March 9, 2009 6:48 AM

Ben said:

Thanks so much!  I hate trying to find the date/time formats in MSDN and never remember how to "get there".  Thanks to this article, I fixed a nasty bug in my application.  

# April 2, 2009 11:16 AM

Carlos Ibarra said:

Thanks for this summary.

You can also format DateTimes inline in a string like this:

Console.WriteLine(String.Format("The current ISO 8601 UTC timestamp is {0:yyyy-MM-ddThh:mm:ss}",DateTime.UtcNow"));

# April 16, 2009 6:13 PM

MynameisBond said:

hi,i got a question about Datetime:

in glob run(for test),Datetime format in Glob run is different ,it changes ":" to ".".even if change it to ":" in contorl panel or use CultureInfo or use datetime.tostring(formatstring),we still get it ".", like 4/17/2009 10.12.

do u have any idea how to with this problem?

tks:)

# May 6, 2009 10:46 PM

Vivek said:

Thanks Buddy it really Usefully

# July 9, 2009 3:24 AM

Al said:

Hi Kathy,

How about a reference for formatting Numbers/Decimals/Currency.

It would be especially useful to show these as BOTH just normal Strings and within a control i.e. with the # binding code

Cheers

# August 13, 2009 5:32 AM

Noble said:

good one..this helped me to finish problems  .. thank you Kathy...

# September 16, 2009 7:53 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker