DateTime
formatFormat codes represent time, and dates, in different ways. Many format patterns can be encountered—many can be handled easily in C#.
We encounter strange codes in DateTime
formats like "M" and "dddd." Here the case of the letters, and the number of them, are important.
Let us examine a simple C# program. Here we combine many format codes. We use a formatting string
with DateTime
and ToString
.
string
specify the output. The final part (in the example) describes the format patterns.using System; // Use current time, with a format string. DateTime time = DateTime.Now; string format = "MMM ddd d HH:mm yyyy"; Console.WriteLine(time.ToString(format));Feb Fri 17 07:11 2023MMM Three-letter month. ddd Three-letter day of the week. d Day of the month. HH Two-digit hours on 24-hour scale. mm Two-digit minutes. yyyy Four-digit year.
Here we modify the format string
to get different output. We change some of the fields. We also use Parse
on the resulting string
.
string
when using DateTime.ParseExact
and TryParseExact
.using System; // Use DateTime format to convert to string. DateTime time = new DateTime(2000, 2, 10); string format = "M/dd/yyyy"; string result = time.ToString(format); Console.WriteLine("RESULT: {0}", result); // Parse string back to DateTime. DateTime parsed = DateTime.Parse(result); Console.WriteLine("PARSED: {0}", parsed);RESULT: 2/10/2000 PARSED: 2/10/2000 12:00:00 AM
Single
-char
formatWe use a char
with ToString
or DateTime.ParseExact
to specify a preset format. These are standard formats. They are useful in many programs.
using System; 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"));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
stringsHere we see the ToLongDateString
, ToLongTimeString
, ToShortDateString
, and ToShortTimeString
methods on DateTime
. These methods use formats.
ToString
with the lowercase and uppercase D and T methods.ToString()
on DateTime
is equivalent to the "G" formatting string
.using System; DateTime now = DateTime.Now; // Equivalent to D. Console.WriteLine(now.ToLongDateString()); // Equivalent to T. Console.WriteLine(now.ToLongTimeString()); // Equivalent to d. Console.WriteLine(now.ToShortDateString()); // Equivalent to t. Console.WriteLine(now.ToShortTimeString()); Console.WriteLine(now.ToString());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
We use the lowercase code "mm" for minutes. Two lowercase "mm" has a leading zero if the number is only one digit long. For minutes, we must use 2 chars.
using System; // Create DateTime with 9 minutes. DateTime nineMinutes = new DateTime(2020, 4, 5, 3, 9, 0); Console.WriteLine("mm: {0}", nineMinutes.ToString("mm"));mm: 09
Seconds are formatted with "fFs." The uppercase F changes how trailing zeros are displayed. And the lowercase "s" changes how leading zeros are displayed.
using System; using static System.Console; DateTime now = DateTime.Now; // Use space after s to avoid one-char date format. string result = now.ToString("s "); WriteLine($"{now} [s] = {result}");12/5/2015 2:04:17 PM [s] = 17
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.
using System; // Create DateTime with 13 hours, or 1 PM. var earlyAfternoon = new DateTime(2020, 1, 1, 13, 0, 0); Console.WriteLine("HH: {0}", earlyAfternoon.ToString("HH"));HH: 13
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.
using System; 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);Two letters: Sat Three letters: Saturday
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 we get from the dddd.
using System; DateTime now = DateTime.Today; for (int i = 0; i < 7; i++) { Console.WriteLine(now.ToString("dddd")); now = now.AddDays(1); }Thursday Friday Saturday Sunday Monday Tuesday Wednesday
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.
using System; DateTime now = DateTime.Today; for (int i = 0; i < 7; i++) { Console.WriteLine(now.ToString("ddd")); now = now.AddDays(1); }Thu Fri Sat Sun Mon Tue Wed
The month is formatted with an uppercase M. One and two Ms display numeric representations. Three and four Ms display string
representations.
using System; // Get month for January. DateTime test = new DateTime(2020, 1, 1); Console.WriteLine("M: {0}", test.ToString("M")); Console.WriteLine("MM: {0}", test.ToString("MM")); Console.WriteLine("MMM: {0}", test.ToString("MMM")); Console.WriteLine("MMMM: {0}", test.ToString("MMMM"));M: January 1 MM: 01 MMM: Jan MMMM: January
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.
using System; // We are in A.D. era. Console.WriteLine(DateTime.Now.ToString("gg"));A.D.
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
.
string
—the value "t" can mean something else in the format string
.string
AM or PM in DateTime
ToString
code.string
.using System; DateTime now = DateTime.Now; for (int i = 0; i < 2; i++) { Console.WriteLine(now.ToString("tt ")); now = now.AddHours(12); }PM AM
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.
using System; 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"));23 23 2023 2023 02023
FormatException
We must pass a valid formatting string
to ToString
on a DateTime
. If we pass something invalid, like an asterisk, we will get a FormatException
.
using System; const string invalid = "*"; string result = DateTime.Today.ToString(invalid);Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.DateTimeFormat.GetRealFormat....
When we format a DateTime
with a format string
that is null
, empty, or missing, we get a default format. We can just omit the argument if we do not have a special format we need.
using System; var date = new DateTime(2000, 1, 1); Console.WriteLine("NULL FORMAT STRING: {0}", date.ToString((string)null)); Console.WriteLine("EMPTY FORMAT STRING: {0}", date.ToString("")); Console.WriteLine("MISSING FORMAT STRING: {0}", date.ToString());NULL FORMAT STRING: 1/1/2000 12:00:00 AM EMPTY FORMAT STRING: 1/1/2000 12:00:00 AM MISSING FORMAT STRING: 1/1/2000 12:00:00 AM
Parse
To go from string
to DateTime
, we can use the Parse()
and TryParse()
methods. Format strings can be provided with ParseExact
.
Many DateTime
formats can be used. We covered single-letter preset format strings. And we handled more complicated, custom strings with character codes.