TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# DateTime Format

This C# tutorial uses DateTime format patterns. It demonstrates format codes and ToString.

DateTime format. A DateTime is converted to a string with a format.

We use the ToString method. This receives many useful formats. Often these formats have confusing syntax forms.

Correct formatting of dates and times is essential. A reference page, like this one, is helpful. With format codes we can reduce code size and make things easier.

Example format string. Here we use a specific formatting string with DateTime and ToString. This is useful when interacting with other systems, or when we require a precise format.

Note: The letters in the format string specify the output. And the final part describes the format patterns.

Based on:

.NET 4.5

C# program that uses DateTime format

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. Here we modify the format string in the above example to get different output. We change some of the fields so the resulting string value is shorter.

Note: You will also need to specify a format string when using DateTime.ParseExact and DateTime.ParseExact.

C# program that uses different format

using System;

class Program
{
    static void Main()
    {
	DateTime time = DateTime.Now;
	string format = "M d h:mm yy";
	Console.WriteLine(time.ToString(format));
    }
}

Output

2 27 11:48 09

Format string pattern

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

Single-char format. We use a char with ToString or DateTime.ParseExact to specify a preset format. These are standard formats. They are useful in many programs.

DateTime.Parse

C# program that tests formats

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. Here we see the ToLongDateString, ToLongTimeString, ToShortDateString, and ToShortTimeString methods on DateTime. These methods use formats.

Note: These methods are equivalent to the lowercase and uppercase D and T methods shown in the example above.

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

string.Format

C# program that uses ToString methods

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. Seconds are formatted with f, F and s. The uppercase F changes how trailing zeros are displayed. And the lowercase s changes how leading zeros are displayed.

Lowercase f: Use the lowercase f to indicate the seconds to one digit length. Use "ff" to indicate the seconds to two digits.

Note: The uppercase F patterns do the same but work differently on trailing zeros.

Lowercase s: The lowercase s displays seconds. With ss we always want two digits, such as 00-59.

Minutes format. We use the lowercase m or mm for minutes. 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. For hours we use "j" and "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.

Statement that prints hours: C#

// Assume it is 1 PM.
Console.WriteLine(DateTime.Now.ToString("HH"));

Output

13

Day format. For days we use one to four d chars. 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".

C# program that uses ddd and dddd

using System;

class Program
{
    static void Main()
    {
	DateTime time = new DateTime(2000, 1, 1);
	// Console.WriteLine and string.Format can handle dates.
	Console.WriteLine("Two letters: {0:ddd}", time);
	Console.WriteLine("Three letters: {0:dddd}", time);
    }
}

Output

Two letters: Sat
Three letters: Saturday

Month format. The month is formatted with an uppercase M. 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 three-letter form of the month represented in the DateTime (like "Jan").

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

Year format. The year format uses the lowercase y letter. We can put one to five characters for the year. It is unlikely we will need five characters.

Tip: For year strings, we use the values "y" through "yyyyy". These display the year to different digits.

However: In your programs, you won't need three digits for the year (yyy), or five.

Misc. 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. We can display the day of the week in a three-letter form. Here we see a simple program that does this. Results vary based on the current language.

C# program that tests days

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 we need to display the complete day of the week, and the four ds together will do this. With Console.WriteLine, we print all seven day strings you can get from the dddd.

Console.WriteLine

C# that shows day strings

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. We can 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 two gs will print.

Statement that prints era: C#

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

Output

A.D.

Month. 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.

DateTime.Month

AM, PM. 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.

C# that displays AM and PM

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. We can vary the number of digits displayed in the year string. We will want to use y, yy, or yyyy for our programs. But five ys is also possible.

Sometimes: Two ys is useful for a user-oriented program, but for back-end code, we will want to use four ys.

C# that displays years

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"));
	Console.WriteLine(now.ToString("yyyy"));
	Console.WriteLine(now.ToString("yyyyy"));
    }
}

Output

9
09
2009
2009
02009

A summary. Many DateTime formats can be used. We covered single-letter preset format strings. And we handled more complicated, custom strings with character codes.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf