TheDeveloperBlog.com

Home | Contact Us

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

<< Back to C-SHARP

C# DateTime Format

Review DateTime format patterns. Call ToString with format codes like MMMM, dd and hh.
DateTime format. The sundial casts a shadow that tells time. The time is formatted upon the stone surface. Format codes represent time, and dates, in different ways.
Character codes. We encounter strange things like "M" and "dddd." Here the case of the letters (and the number of them) are important.
First example. Let us examine a simple C# program. Here we combine many format codes. We use a formatting string with DateTime and ToString.DateTime

Note: The letters in the format string specify the output. The final part (in the example) describes the format patterns.

C# program that uses DateTime format using System; class Program { static void Main() { // Use current time, with a format string. DateTime time = DateTime.Now; string format = "MMM ddd d HH:mm yyyy"; Console.WriteLine(time.ToString(format)); } } Output Feb Tue 21 13:15 2017 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
Modified format. Here we modify the format string to get different output. We change some of the fields—the resulting string value is shorter.

Also: We 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 calling ToString with the lowercase and uppercase D and T methods.

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; // 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()); } } 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
Minutes format. We use the lowercase code "mm" for minutes. Two lowercase ms has a leading zero if the number is only one digit long. For minutes, we must use 2 chars.

Info: Just one "m" does not return minutes—it returns the month and day. The previous version of this page had an error here.

C# program that shows minute part using System; class Program { static void Main() { // Create DateTime with 9 minutes. DateTime nineMinutes = new DateTime(2020, 4, 5, 3, 9, 0); Console.WriteLine("mm: {0}", nineMinutes.ToString("mm")); } } Output mm: 09
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.

C# program that uses s format using System; using static System.Console; class Program { static void Main() { DateTime now = DateTime.Now; // Use space after s to avoid one-char date format. string result = now.ToString("s "); WriteLine($"{now} [s] = {result}"); } } Output 12/5/2015 2:04:17 PM [s] = 17
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.

C# program that uses hours format using System; class Program { static void Main() { // 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")); } } Output HH: 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
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 we get from the dddd.Console
C# program 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
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
Month format. The month is formatted with an uppercase M. One and two Ms display numeric representations. Three and four Ms display string representations.DateTime.Month

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

C# program that uses month formats using System; class Program { static void Main() { // 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")); } } Output M: January 1 MM: 01 MMM: Jan MMMM: January
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.
C# program that prints current era using System; class Program { static void Main() { // We are in A.D. era. Console.WriteLine(DateTime.Now.ToString("gg")); } } Output A.D.
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# program 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.

Info: In almost all programs, we will not need three or five digits for the year, but these codes exist.

C# program 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
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.
C# program that causes FormatException using System; class Program { static void Main() { const string invalid = "*"; string result = DateTime.Today.ToString(invalid); } } Output Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.DateTimeFormat.GetRealFormat....
Null. When we form at 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.
C# program that uses null, empty, missing formats using System; class Program { static void Main() { 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()); } } Output 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
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 "/".

Parse. To go from string to DateTime, we can use the Parse() and TryParse() methods. Format strings can be provided with ParseExact.
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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