C# DateTime Format

Time

Many DateTime formats are available. We use the ToString method on the DateTime type. ToString receives many useful formats. Often these formats have confusing syntax forms. Correct formatting of dates and times is essential.

DateTime

Format string

To start, we use a specific formatting string with DateTime and ToString to obtain a special DateTime string. This is useful when interacting with other systems, or when you require a precise format.

Format

Note:The letters in the format string above specify the output. The final comment shows what effect the format patterns have.

Based on:

.NET 4.5

Program that uses DateTime format: C#

using System;

class Program
{
    static void Main()
    {
	DateTime time = DateTime.Now;              // Use current time
	string format = "MMM ddd d HH:mm yyyy";    // Use this format
	Console.WriteLine(time.ToString(format));  // Write to console
    }
}

Output

Feb Fri 27 11:41 2009

Format string pattern

MMM     display three-letter month
ddd     display three-letter day of the WEEK
d       display day of the MONTH
HH      display two-digit hours on 24-hour scale
mm      display two-digit minutes
yyyy    display four-digit year

Modify format

String type

Continuing on, we modify the DateTime format string in the above example to get different output with ToString. We change some of the fields so the resulting string value is shorter.

Format string usages. You will also need to specify a format string when using DateTime.ParseExact and DateTime.ParseExact. This is because those methods require a custom pattern to parse.

Program that uses different format: C#

using System;

class Program
{
    static void Main()
    {
	DateTime time = DateTime.Now;             // Use current time
	string format = "M d h:mm yy";            // Use this format
	Console.WriteLine(time.ToString(format)); // Write to console
    }
}

Output

2 27 11:48 09

Format string pattern

M       display one-digit month number          [changed]
d       display one-digit day of the MONTH      [changed]
h       display one-digit hour on 12-hour scale [changed]
mm      display two-digit minutes
yy      display two-digit year                  [changed]

Single-char format

Next you can use a single char with ToString or DateTime.ParseExact to specify a preset format. These are standard formats and useful in many programs. They can eliminate typos in the custom format strings.

DateTime.Parse
Program that tests formats: C#

using System;

class Program
{
    static void Main()
    {
	DateTime now = DateTime.Now;
	Console.WriteLine(now.ToString("d"));
	Console.WriteLine(now.ToString("D"));
	Console.WriteLine(now.ToString("f"));
	Console.WriteLine(now.ToString("F"));
	Console.WriteLine(now.ToString("g"));
	Console.WriteLine(now.ToString("G"));
	Console.WriteLine(now.ToString("m"));
	Console.WriteLine(now.ToString("M"));
	Console.WriteLine(now.ToString("o"));
	Console.WriteLine(now.ToString("O"));
	Console.WriteLine(now.ToString("s"));
	Console.WriteLine(now.ToString("t"));
	Console.WriteLine(now.ToString("T"));
	Console.WriteLine(now.ToString("u"));
	Console.WriteLine(now.ToString("U"));
	Console.WriteLine(now.ToString("y"));
	Console.WriteLine(now.ToString("Y"));
    }
}

Output

d    2/27/2009
D    Friday, February 27, 2009
f    Friday, February 27, 2009 12:11 PM
F    Friday, February 27, 2009 12:12:22 PM
g    2/27/2009 12:12 PM
G    2/27/2009 12:12:22 PM
m    February 27
M    February 27
o    2009-02-27T12:12:22.1020000-08:00
O    2009-02-27T12:12:22.1020000-08:00
s    2009-02-27T12:12:22
t    12:12 PM
T    12:12:22 PM
u    2009-02-27 12:12:22Z
U    Friday, February 27, 2009 8:12:22 PM
y    February, 2009
Y    February, 2009

Date strings

Note

Here we see the ToLongDateString, ToLongTimeString, ToShortDateString, and ToShortTimeString methods on DateTime. These methods are equivalent to the lowercase and uppercase D and T methods shown in the example above.

Note:The default ToString on DateTime is equivalent to the "G" formatting string. ToString("G") and ToString() do the same thing.

string.Format
Program that uses ToString methods: C#

using System;

class Program
{
    static void Main()
    {
	DateTime now = DateTime.Now;
	Console.WriteLine(now.ToLongDateString());  // Equivalent to D
	Console.WriteLine(now.ToLongTimeString());  // Equivalent to T
	Console.WriteLine(now.ToShortDateString()); // Equivalent to d
	Console.WriteLine(now.ToShortTimeString()); // Equivalent to t
	Console.WriteLine(now.ToString());
    }
}

Output

ToLongDateString     Friday, February 27, 2009
ToLongTimeString     12:16:59 PM
ToShortDateString    2/27/2009
ToShortTimeString    12:16 PM
ToString             2/27/2009 12:16:59 PM

Seconds format

The current time: now

Seconds are formatted with the lowercase f, the uppercase F, and the lowercase s. The uppercase F changes how trailing zeros are displayed. And the lowercase s changes how leading zeros are displayed.

Use the lowercase f to indicate the seconds to one digit length. Use two lowercase fs (ff) to indicate the seconds to two digits. The uppercase F patterns do the same but work differently on trailing zeros.

The lowercase s displays seconds. A single lowercase s means that you do not require a leading zero. Two lowercase s characters (ss) means you always want two digits, such as 00-59.

Minutes format

Next, DateTime format strings use the lowercase m or mm for minutes. You can use one or two lowercase ms. Two lowercase ms has a leading zero if the number is only one digit long. This is the only difference.

Tip:The two ms means that there are always two digits displayed, with a leading zero if necessary.

Hours format

Squares

In DateTime formats, hours are represented with lowercase h and uppercase H. You can use one or two characters. The lowercase h is used for a 12-hour clock. The uppercase H is a 24-hour clock.

Value h:Display the hours in one digit if possible.
If the hours is greater than 9, it will display two digits.
Range is 1-12.

Value hh:Display the hours in two digits always, even if the hour is one digit. The range here will be 01-12.

Value H:This represents the hours in a range of 0-23, which is called military time in some parts of the world.

Value HH:This returns the hours in a range of 00-23. With a single H, there is always a leading zero if the number is one digit.

Day format

Note

The formats "d" and "dd" (one and two ds) mean something different from "ddd" and "dddd" (three and four ds). One "d" and "dd" indicate the day of the month, while "ddd" and "dddd" indicate the day of the week, in a word.

Value d:Use this to specify the numeric value for the day of the month. It will be one or two digits long.

Value dd:This is the same as a single d, except there are always two digits, with a leading 0 prepended if necessary.

Value ddd:This displays a three-letter string that indicates the current day of the week.

Value dddd:This displays the full string for the day of the week.
An example would be "Saturday".

Month format

DateTime

In DateTime format strings, the month is formatted with an uppercase M. You can use one to four Ms. One and two Ms display numeric representations. Three and four Ms display string representations.

M, MM:These display the months in numeric form.
One M does not have a leading zero on it.
Two Ms have a leading zero.

MMM:This displays the abbreviated three-letter form of the month represented in the DateTime.

MMMM:This displays the full month string, properly capitalized.
An example is "January".

Year format

The year uses the lowercase y letter. You can put one to five characters for the year. It is unlikely you will need five characters any time soon. For year strings, we use the values "y" through "yyyyy".

Tip:These display the year to different digits. In your programs, you won't need three digits for the year (yyy), or five.

Misc.

Miscellaneous

Even more DateTime formatting characters are available. You can change how AM and PM are displayed. You can display AD and BC. You can show the UTC offset and even display time zones.

Value t:Use the lowercase t to indicate A, when the time is in the AM, and P, for when the time is in PM.

Value tt:Use two lowercase tts to display the full AM or PM string. You will normally want this for displaying the string to a user.

Value gg:Use this to display AD on your date.
It is unlikely that this will be BC in most programs.

Value k:Use this to display time zone information.
This is often not needed in programs.

Values z, zz, zzz:These represent the offset from the UTC time on the local operating system.

Colon and slash:The colon is the time separator ":".
The slash the date separator "/".

Three-letter days

It may be useful to display the day of the week in a three-letter form. Here we see a simple program that prints out the days of the week in three-letter format. This will vary based on the language installed on the computer.

Program that tests days: C#

using System;

class Program
{
    static void Main()
    {
	DateTime now = DateTime.Today;
	for (int i = 0; i < 7; i++)
	{
	    Console.WriteLine(now.ToString("ddd"));
	    now = now.AddDays(1);
	}
    }
}

Output

Thu
Fri
Sat
Sun
Mon
Tue
Wed

Complete day

Often you need to display the complete day of the week in your C# code, and the four ds together will do this. With Console.WriteLine, we print all seven different day strings you can get from the dddd.

Console.WriteLine
Program that shows day strings: C#

using System;

class Program
{
    static void Main()
    {
	DateTime now = DateTime.Today;
	for (int i = 0; i < 7; i++)
	{
	    Console.WriteLine(now.ToString("dddd"));
	    now = now.AddDays(1);
	}
    }
}

Output

Thursday
Friday
Saturday
Sunday
Monday
Tuesday
Wednesday

Era

Framework: NET

The .NET Framework allows you to display the date with the era or period—usually AD or BC. It is unlikely that you will need to use BC, except in a rare theoretical application. Here is what the two gs will print.

Statement that prints era: C#

Console.WriteLine(DateTime.Now.ToString("gg"));

Output

A.D.

Month

Letters of the alphabet: ABC

Programs have different formatting requirements for month names. Sometimes, the first three letters of the name are needed. This helps in tabular or spreadsheet displays. More details and examples are available.

DateTime.Month

AM, PM

This isn't something you are likely to need, but interesting to find out. When you specify one t, you can get the first letter of the AM or PM string. This is equivalent to using Substring or getting the first char of the tt string.

Tip:There is a space at the end of the format string—the value "t" can mean something else in the format string.

Next:We show a program that gets the string AM or PM in DateTime ToString code.

Note:There are no periods in the output of tt. If you require periods in your AM or PM, you would have to manipulate the string.

Program that displays AM and PM: C#

using System;

class Program
{
    static void Main()
    {
	DateTime now = DateTime.Now;
	for (int i = 0; i < 2; i++)
	{
	    Console.WriteLine(now.ToString("tt "));
	    now = now.AddHours(12);
	}
    }
}

Output

PM
AM

Year

You can vary the number of digits displayed in the year string. You will always want to use y, yy, or yyyy for your programs. The .NET Framework accepts different numbers, but they are impractical in the real world.

Note:Occasionally two ys is useful for a user-oriented program, but for your back end code, you will want to use four ys.

Program that displays years: C#

using System;

class Program
{
    static void Main()
    {
	DateTime now = DateTime.Now;
	Console.WriteLine(now.ToString("y "));
	Console.WriteLine(now.ToString("yy"));
	Console.WriteLine(now.ToString("yyy"));   // <-- Don't use this
	Console.WriteLine(now.ToString("yyyy"));
	Console.WriteLine(now.ToString("yyyyy")); // <-- Don't use this
    }
}

Output

9
09
2009
2009
02009

Summary

We used DateTime format strings. We covered single-letter preset format strings, and more complicated custom format strings with different character codes. We saw an overview of the custom code letters.

Finally:We saw enumerations of all the values for days of the week and months—and three-letter versions of those.


C#: Time