C# DateTime Format

Embed Size (px)

Citation preview

C# DateTime FormatString Format for DateTime [C#] This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method. Custom DateTime Formatting There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed),t (P.M or A.M) and z (time zone). Following examples demonstrate how are the format specifiers rewritten to the output. [C#] // create date time 2008-03-09 16:05:07.123 DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123); String.Format("{0:y yy yyy yyyy}", dt); String.Format("{0:M MM MMM MMMM}", dt); String.Format("{0:d dd ddd dddd}", dt); String.Format("{0:h hh H HH}", String.Format("{0:m mm}", String.Format("{0:s ss}", dt); dt); dt); // "8 08 008 2008" // "3 03 Mar March" // "4 04 16 16" // "5 05" // "7 07" // "1 12 123 1230" // "1 12 123 123" // "P PM" // "-6 -06 -06:00" year month hour 12/24 minute second sec.fraction without zeroes A.M. or P.M. time zone

// "9 09 Sun Sunday" day

String.Format("{0:f ff fff ffff}", dt); String.Format("{0:F FF FFF FFFF}", dt); String.Format("{0:t tt}", String.Format("{0:z zz zzz}", dt); dt);

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator andDateTimeFormatInfo.TimeSeparator. [C#] // date separator in german culture is "." (so "/" changes to ".") String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US) String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE) Here are some examples of custom date and time formatting: [C#] // month/day numbers without/with leading zeroes String.Format("{0:M/d/yyyy}", dt); String.Format("{0:MM/dd/yyyy}", dt); // day/month names String.Format("{0:ddd, MMM d, yyyy}", dt); String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sun, Mar 9, 2008" // "Sunday, March 9, 2008" // "3/9/2008" // "03/09/2008"

// two/four digit year String.Format("{0:MM/dd/yy}", dt); String.Format("{0:MM/dd/yyyy}", dt); Standard DateTime Formatting In DateTimeFormatInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture. Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First column contains format specifiers for the String.Format method. // "03/09/08" // "03/09/2008"

Specifier t d T D f F g G m, M y, Y r, R s u

DateTimeFormatInfo property ShortTimePattern ShortDatePattern LongTimePattern LongDatePattern (combination of D and t) FullDateTimePattern (combination of d and t) (combination of d and T)

Pattern value (for en-US culture) h:mm tt M/d/yyyy h:mm:ss tt dddd, MMMM dd, yyyy dddd, MMMM dd, yyyy h:mm tt dddd, MMMM dd, yyyy h:mm:ss tt M/d/yyyy h:mm tt M/d/yyyy h:mm:ss tt MMMM dd MonthDayPattern MMMM, yyyy YearMonthPattern ddd, dd MMM yyyy HH':'mm':'ss RFC1123Pattern 'GMT' (*) yyyy'-'MM'-'dd'T'HH':'mm':'ss (*) SortableDateTimePattern UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*) (*) = culture independent

Following examples show usage of standard format specifiers in String.Format method and the resulting output. [C#] String.Format("{0:t}", dt); String.Format("{0:d}", dt); String.Format("{0:T}", dt); String.Format("{0:D}", dt); String.Format("{0:f}", dt); String.Format("{0:F}", dt); String.Format("{0:g}", dt); String.Format("{0:G}", dt); String.Format("{0:m}", dt); String.Format("{0:y}", dt); String.Format("{0:r}", dt); String.Format("{0:s}", dt); String.Format("{0:u}", dt); UniversalSortableDateTime // "4:05 PM" // "3/9/2008" // "4:05:07 PM" // "Sunday, March 09, 2008" // "Sunday, March 09, 2008 4:05 PM" // "3/9/2008 4:05 PM" // "3/9/2008 4:05:07 PM" // "March 09" // "March, 2008" // "Sun, 09 Mar 2008 16:05:07 GMT" // "2008-03-09T16:05:07" // "2008-03-09 16:05:07Z" ShortTime ShortDate LongTime LongDate LongDate+ShortTime ShortDate+ShortTime ShortDate+LongTime MonthDay YearMonth RFC1123 SortableDateTime

// "Sunday, March 09, 2008 4:05:07 PM" FullDateTime

========================

You need help with DateTime format strings in the C# language or other .NET languages. The framework provides powerful formatting capabilities, but the syntax is confusing and there are some tricks. Here we see examples of using DateTime formats, and also the different values you can get with the individual formats.Format your DateTimes for your application. You will not have to write elaborate custom routines. The .NET Framework has a powerful DateTime format mechanism.

DateTime format stringHere we see an example of how you can 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.=== Program that uses DateTime format [C#] ===

using System;

class Program { static void Main() { DateTime time = DateTime.Now; // Use current time // Use this format

string format = "MMM ddd d HH:mm yyyy";

Console.WriteLine(time.ToString(format)); // Write to console } }

=== Output of the program ===

Feb Fri 27 11:41 2009

=== Format string pattern ===

MMM ddd d HH mm yyyy

display three-letter month display three-letter day of the WEEK display day of the MONTH display two-digit hours on 24-hour scale display two-digit minutes display four-digit year

Notes on the letters. The letters in the format string above specify the output you want to display. The final comment shows what the MMM, ddd, d, HH, mm, and yyyy will do.

Modify formatHere we see how you can modify the DateTime format string in the above example to get different output with ToString. We change some of the fields so the resulting value is shorter.=== Program that uses different format [C#] ===

using System;

class Program { static void Main() { DateTime time = DateTime.Now; string format = "M d h:mm yy"; // Use current time // Use this format

Console.WriteLine(time.ToString(format)); // Write to console

} }

=== Output of the program ===

2 27 11:48 09

=== Format string pattern ===

M d h mm yy

display one-digit month number display one-digit day of the MONTH

[changed] [changed]

display one-digit hour on 12-hour scale [changed] display two-digit minutes display two-digit year [changed]

Note on 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.

Single-letter formatHere we see that you can use a single character with ToString or DateTime.ParseExact to specify a preset format available in the framework. These are standard formats and very useful in many programs. They can eliminate typos in the custom format strings.=== 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 of the program ===

d D f

2/27/2009 Friday, February 27, 2009 Friday, February 27, 2009 12:11 PM

F g G m M o O s t T u U y Y

Friday, February 27, 2009 12:12:22 PM 2/27/2009 12:12 PM 2/27/2009 12:12:22 PM February 27 February 27 2009-02-27T12:12:22.1020000-08:00 2009-02-27T12:12:22.1020000-08:00 2009-02-27T12:12:22 12:12 PM 12:12:22 PM 2009-02-27 12:12:22Z Friday, February 27, 2009 8:12:22 PM February, 2009 February, 2009

Date stringsHere 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.=== 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 of the program ===

ToLongDateString ToLongTimeString ToShortDateString ToShortTimeString ToString

Friday, February 27, 2009 12:16:59 PM 2/27/2009 12:16 PM

2/27/2009 12:16:59 PM

Note on default ToString method. The default ToString method on DateTime shown above is equivalent to the simple "G" formatting string in the previous example. In other words, ToString("G") and ToString() do the same thing.

Format charactersWhen you use DateTime.ParseExact, or ToString(), you need to specify a formatting string, which is a sequence of characters that designate how the final result will look. What follows are my notes on the strings from MSDN.See 24-Hour and Military Time Formats. d Use this to specify the numeric value for the day of the month. It will be one or two digits long. dd This is the same as a single d, except there are always two

digits, with a leading 0 prepended if necessary. ddd This displays a three-letter string that indicates the current day of the week. dddd This displays the full string for the day of the week. f ff fff ffff fffff ffffff fffffff F FF FFF FFFF FFFFF FFFFFF FFFFFFF Use the lowercase f to indicate the seconds to one digit length. Use two lowercase fs to indicate the seconds to two digits. The uppercase F patterns do the same but work differently on trailing zeros. gg Use this to display A.D. on your date. It is unlikely that this will be B.C. in most programs. 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. hh Display the hours in two digits always, even if the hour is one digit. The range here will be 01-12.

H This represents the hours in a range of 0-23, which is called military time in some parts of the world. HH This represents the hours in a range of 00-23. The only different here between the single H is that there is always a leading zero if the number is one digit. K Use this to display time zone information. m mm This formats the minutes in your date format string. Here, the one m means that there is only one digit displayed if possible. The two ms means that there are always two digits displayed, with a leading zero if necessary. M MM These display the months in numeric form. The one uppercase M does not have a leading zero on it. The two uppercase Ms will format a number with a leading zero if it is required. MMM This displays the abbreviated three-letter form of the month represented in the DateTime. MMMM This displays the full month string, properly capitalized. s ss The lowercase s displays seconds. A single lowercase s means that you do not require a leading zero. Two lowercase s characters means you always want two digits, such as 00-59. t Use the lowercase t to indicate A, when the time is in the AM,

and P, for when the time is in PM. tt Use two lowercase tts to display the full AM or PM string. You will normally want this for when you are displaying the string to a user. y yy yyy yyyy yyyyy These display the year to different digits. In your programs, you won't need three digits for the year, or five. Therefore, you should only consider one y, two ys, or four ys. z zz zzz These represent the offset from the UTC time on the local operating system. : This is the time separator. / This is the date separator.

Difference between d and dd, ddd and dddd. It is important to note that d and dd (one and two ds) mean something entirely different than ddd and dddd (three and four ds). d and dd indicate the day of the month, while ddd and dddd indicate the day of the week, in a word.

Three-letter daysIn some systems 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 of the program ===

Thu Fri Sat Sun Mon Tue Wed

Display complete dayOften you need to display the complete day of the week in your C# code, and the four ds together will do this for you. This simple program shows all seven different day strings you can get from the dddd.

=== 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 of the program ===

Thursday Friday Saturday Sunday Monday Tuesday Wednesday

Display the eraThe .NET platform allows you to display the date with the era or period, which is usually A.D. or B.C. It is unlikely that you will need to use B.C., except in a rare theoretical application. Nevertheless, here is what the two gs will print. Use the code "DateTime.Now.ToString("gg");".

Month formatYou may need to display the month name in a three-letter format. This is equivalent, in English, to taking a substring of the first three letters, but using the three Ms next to each other may be easier and more terse for your code. Additionally, you may want full month strings. This site contains a useful article that covers DateTime month strings and the Month property in more detail.See DateTime.Month Property.

Display AM/PMThis 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. There is a space at the end of the format string because the value "t" can mean something else in the format string. Full string. Here we see how you can get the string AM or PM in your DateTime ToString code. The code adds 12 to ensure the second iteration is in the other half.=== 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 of the program ===

PM AM

Note on lack of periods. There are no periods in the output of tt in the example above. Therefore, if you require periods in your AM or PM, you would have to manipulate the string.

Display yearYou 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 framework accepts different numbers, but they are impractical in the real world. Occasionally two ys is useful for a user-oriented program, but for your back end code, you will want to use four ys. You do not need uppercase 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")); Console.WriteLine(now.ToString("yyyy")); Console.WriteLine(now.ToString("yyyyy")); // 6/15/2009 (enUS) 6/15/2009 1:45:30 PM -> 15/06/2009 (frFR) 6/15/2009 1:45:30 PM -> 2009/06/15 (jaJP) 6/15/2009 1:45:30 PM -> Monday, June 15, 2009 (en-US) 6/15/2009 1:45:30 PM -> 15 2009 . (ru-RU) 6/15/2009 1:45:30 PM -> Montag, 15. Juni 2009 (de-DE) 6/15/2009 1:45:30 PM -> Monday, June 15, 2009 1:45 PM (en-US) 6/15/2009 1:45:30 PM -> den 15 juni 2009 13:45 (sv-SE) 6/15/2009 1:45:30 PM -> , 15 2009 1:45 (el-GR) 6/15/2009 1:45:30 PM -> Monday, June 15, 2009 1:45:30 PM (en-US) 6/15/2009 1:45:30 PM -> den 15 juni 2009 13:45:30 (sv-SE) 6/15/2009 1:45:30 PM -> , 15 2009 1:45:30 (el-GR)

"d"

Short date pattern. More information: The Short Date ("d") Format Specifier.

"D"

Long date pattern. More information: The Long Date ("D") Format Specifier.

"f"

Full date/time pattern (short time). More information: The Full Date Short Time ("f") Format Specifier.

"F"

Full date/time pattern (long time). More information: The Full Date Long Time ("F") Format Specifier.

"g"

6/15/2009 1:45:30 PM -> 6/15/2009 1:45 PM (en-US) General date/time pattern (short time). 6/15/2009 1:45:30 PM -> 15/06/2009 13:45 More information: The General Date (es-ES) Short Time ("g") Format Specifier. 6/15/2009 1:45:30 PM -> 2009/6/15 13:45 (zh-CN) 6/15/2009 1:45:30 PM -> 6/15/2009 1:45:30 PM (en-US) General date/time pattern (long time). 6/15/2009 1:45:30 PM -> 15/06/2009 More information: The General Date 13:45:30 (es-ES) Long Time ("G") Format Specifier. 6/15/2009 1:45:30 PM -> 2009/6/15 13:45:30 (zh-CN) Month/day pattern. 6/15/2009 1:45:30 PM -> June 15 (en-US) More information: The Month ("M", 6/15/2009 1:45:30 PM -> 15. juni (da-DK)

"G"

"M", "m"

"m") Format Specifier. "O", "o" Round-trip date/time pattern. More information: The Round-trip ("O", "o") Format Specifier. RFC1123 pattern. More information: The RFC1123 ("R", "r") Format Specifier. Sortable date/time pattern. More information: The Sortable ("s") Format Specifier. Short time pattern. More information: The Short Time ("t") Format Specifier. Long time pattern. More information: The Long Time ("T") Format Specifier.

6/15/2009 1:45:30 PM -> 15 Juni (id-ID) 6/15/2009 1:45:30 PM -> 2009-0615T13:45:30.0900000 6/15/2009 1:45:30 PM -> Mon, 15 Jun 2009 20:45:30 GMT 6/15/2009 1:45:30 PM -> 2009-0615T13:45:30 6/15/2009 1:45:30 PM -> 1:45 PM (en-US) 6/15/2009 1:45:30 PM -> 13:45 (hr-HR) 6/15/2009 1:45:30 PM -> 01:45 ( ar-EG) 6/15/2009 1:45:30 PM -> 1:45:30 PM (enUS) 6/15/2009 1:45:30 PM -> 13:45:30 (hr-HR) 6/15/2009 1:45:30 PM -> 01:45:30 ( arEG)

"R", "r"

"s"

"t"

"T"

"u"

Universal sortable date/time pattern. 6/15/2009 1:45:30 PM -> 2009-06-15 More information: The Universal 20:45:30Z Sortable ("u") Format Specifier. Universal full date/time pattern. More information: The Universal Full ("U") Format Specifier. 6/15/2009 1:45:30 PM -> Monday, June 15, 2009 8:45:30 PM (en-US) 6/15/2009 1:45:30 PM -> den 15 juni 2009 20:45:30 (sv-SE) 6/15/2009 1:45:30 PM -> , 15 2009 8:45:30 (el-GR) 6/15/2009 1:45:30 PM -> June, 2009 (enUS) 6/15/2009 1:45:30 PM -> juni 2009 (daDK) 6/15/2009 1:45:30 PM -> Juni 2009 (id-ID) Throws a run-time FormatException.

"U"

"Y", "y"

Year month pattern. More information: The Year Month ("Y") Format Specifier.

Any other Unknown specifier. single characterHow Standard Format Strings Work

In a formatting operation, a standard format string is simply an alias for a custom format string. The advantage of using an alias to refer to a custom format string is that, although the alias remains invariant, the custom format string itself can vary. This is important because the string representations of date and time values typically vary by culture. For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".

If a standard format string in a formatting operation maps to a particular culture's custom format string, your application can define the specific culture whose custom format strings are used in one of these ways: You can use the default (or current) culture. The following example displays a date using the current culture's short date format. In this case, the current culture is en-US.

VB C# C++ F# JScript Copy // Display using current (en-us) culture's short date format DateTime thisDate = new DateTime(2008, 3, 15); Console.WriteLine(thisDate.ToString("d")); // Displays 3/15/2008

You can pass a CultureInfo object representing the culture whose formatting is to be used toa method that has an IFormatProvider parameter. The following example displays a date using the short date format of the pt-BR culture.

VB C# C++ F# JScript Copy // Display using pt-BR culture's short date format DateTime thisDate = new DateTime(2008, 3, 15); CultureInfo culture = new CultureInfo("pt-BR"); Console.WriteLine(thisDate.ToString("d", culture)); // Displays 15/3/2008

You can pass a DateTimeFormatInfo object that provides formatting information to amethod that has an IFormatProvider parameter. The following example displays a date using the short date format from a DateTimeFormatInfo object for the hr-HR culture.

VB C# C++ F# JScript Copy // Display using date format information from hr-HR culture DateTime thisDate = new DateTime(2008, 3, 15); DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat; Console.WriteLine(thisDate.ToString("d", fmt)); // Displays 15.3.2008In some cases, the standard format string serves as a convenient abbreviation for a longer custom format string that is invariant. Four standard format strings fall into this category: "O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures. The following table provides information on these four standard date and time format strings.

Standard format string

Defined by DateTimeFormatInfo.InvariantInfo property

Custom format string

"O" or "o" "R" or "r" "s" "u"

None RFC1123Pattern SortableDateTimePattern UniversalSortableDateTimePattern

yyyy'-'MM'-'dd'T'HH':'mm' :'ss'.'fffffffzz ddd, dd MMM yyyy HH':'mm':'ss 'GMT' yyyy'-'MM'-'dd'T'HH':'mm' :'ss yyyy'-'MM'-'dd HH':'mm':'ss'Z'

Standard format strings can also be used in parsing operations with the DateTime.ParseExact or DateTimeOffset.ParseExact methods, which require an input string to exactly conform to a particular pattern for the parse operation to succeed. Many standard format strings map to multiple custom format strings, so a date and time value can be represented in a variety of formats and the parse operation will still succeed. You can determine the custom format string or strings that correspond to a standard format string by calling the DateTimeFormatInfo.GetAllDateTimePatterns(Char) method. The following example displays the custom format strings that map to the "d" (short date pattern) standard format string.

VB C# C++ F# JScript Copy using System; using System.Globalization;public class Example { public static void Main() { Console.WriteLine("'d' standard format string:"); foreach (var customString in DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns('d')) Console.WriteLine(" {0}", customString); } } // The example displays the following output: // 'd' standard format string: // M/d/yyyy // M/d/yy // MM/dd/yy // MM/dd/yyyy // yy/MM/dd // yyyy-MM-dd // dd-MMM-yy The following sections describe the standard format specifiers for DateTime and DateTimeOffset values. The Short Date ("d") Format Specifier

The "d" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.ShortDatePattern property. For example, the custom format string that is returned by the ShortDatePattern property of the invariant culture is "MM/dd/yyyy".

The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned string.

Property

Description

ShortDatePattern Defines the overall format of the result string. DateSeparatorVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008,4, 10); Console.WriteLine(date1.ToString("d", DateTimeFormatInfo.InvariantInfo)); // Displays 04/10/2008 Console.WriteLine(date1.ToString("d", CultureInfo.CreateSpecificCulture("en-US"))); // Displays 4/10/2008 Console.WriteLine(date1.ToString("d", CultureInfo.CreateSpecificCulture("en-NZ"))); // Displays 10/04/2008 Console.WriteLine(date1.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"))); // Displays 10.04.2008Back to table The Long Date ("D") Format Specifier

Defines the string that separates the year, month, and day components of a date.

The following example uses the "d" format specifier to display a date and time value.

The "D" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.LongDatePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy".The following table lists the properties of the DateTimeFormatInfo object that control the formatting of the returned string.

Property

Description

LongDatePattern Defines the overall format of the result string. DayNames MonthNamesVB C# C++ F# JScript Copy

Defines the localized day names that can appear in the result string. Defines the localized month names that can appear in the result string.

The following example uses the "D" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10); Console.WriteLine(date1.ToString("D", CultureInfo.CreateSpecificCulture("en-US"))); // Displays Thursday, April 10, 2008 Console.WriteLine(date1.ToString("D", CultureInfo.CreateSpecificCulture("pt-BR"))); // Displays quinta-feira, 10 de abril de 2008 Console.WriteLine(date1.ToString("D", CultureInfo.CreateSpecificCulture("es-MX"))); // Displays jueves, 10 de abril de 2008Back to table The Full Date Short Time ("f") Format Specifier

The "f" standard format specifier represents a combination of the long date ("D") and short time ("t") patterns, separated by a space.The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier returned by the DateTimeFormatInfo.LongDatePattern and DateTimeFormatInfo.ShortTimePatternproperties of some cultures may not make use of all properties.

Property

Description

LongDatePattern Defines the format of the date component of the result string. ShortTimePattern Defines the format of the time component of the result string. DayNames MonthNames TimeSeparator AMDesignator PMDesignatorVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("f", CultureInfo.CreateSpecificCulture("en-US"))); // Displays Thursday, April 10, 2008 6:30 AM Console.WriteLine(date1.ToString("f", CultureInfo.CreateSpecificCulture("fr-FR"))); // Displays jeudi 10 avril 2008 06:30

Defines the localized day names that can appear in the result string. Defines the localized month names that can appear in the result string. Defines the string that separates the hour, minute, and second components of a time. Defines the string that indicates times from midnight to before noon in a 12hour clock. Defines the string that indicates times from noon to before midnight in a 12hour clock.

The following example uses the "f" format specifier to display a date and time value.

Back to table The Full Date Long Time ("F") Format Specifier

The "F" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.FullDateTimePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy HH:mm:ss".The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by theFullDateTimePattern property of some cultures may not make use of all properties.

Property

Description

FullDateTimePattern Defines the overall format of the result string. DayNames MonthNames TimeSeparator AMDesignator PMDesignatorVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("F", CultureInfo.CreateSpecificCulture("en-US"))); // Displays Thursday, April 10, 2008 6:30:00 AM Console.WriteLine(date1.ToString("F", CultureInfo.CreateSpecificCulture("fr-FR"))); // Displays jeudi 10 avril 2008 06:30:00Back to table The General Date Short Time ("g") Format Specifier

Defines the localized day names that can appear in the result string. Defines the localized month names that can appear in the result string. Defines the string that separates the hour, minute, and second components of a time. Defines the string that indicates times from midnight to before noon in a 12hour clock. Defines the string that indicates times from noon to before midnight in a 12hour clock.

The following example uses the "F" format specifier to display a date and time value.

The "g" standard format specifier represents a combination of the short date ("d") and short time ("t") patterns, separated by a space.The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object

properties that may control the formatting of the returned string. The custom format specifier that is returned by the DateTimeFormatInfo.ShortDatePattern andDateTimeFormatInfo.ShortTimePattern properties of some cultures may not make use of all properties.

Property

Description

ShortDatePattern Defines the format of the date component of the result string. ShortTimePattern Defines the format of the time component of the result string. DateSeparator TimeSeparator AMDesignator PMDesignatorVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("g", DateTimeFormatInfo.InvariantInfo)); // Displays 04/10/2008 06:30 Console.WriteLine(date1.ToString("g", CultureInfo.CreateSpecificCulture("en-us"))); // Displays 4/10/2008 6:30 AM Console.WriteLine(date1.ToString("g", CultureInfo.CreateSpecificCulture("fr-BE"))); // Displays 10/04/2008 6:30Back to table The General Date Long Time ("G") Format Specifier

Defines the string that separates the year, month, and day components of a date. Defines the string that separates the hour, minute, and second components of a time. Defines the string that indicates times from midnight to before noon in a 12hour clock. Defines the string that indicates times from noon to before midnight in a 12hour clock.

The following example uses the "g" format specifier to display a date and time value.

The "G" standard format specifier represents a combination of the short date ("d") and long time ("T") patterns, separated by a space.The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by the DateTimeFormatInfo.ShortDatePattern andDateTimeFormatInfo.LongTimePattern properties of some cultures may not make use of all properties.

Property

Description

ShortDatePattern Defines the format of the date component of the result string.

LongTimePattern Defines the format of the time component of the result string. DateSeparator TimeSeparator AMDesignator PMDesignatorVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("G", DateTimeFormatInfo.InvariantInfo)); // Displays 04/10/2008 06:30:00 Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("en-us"))); // Displays 4/10/2008 6:30:00 AM Console.WriteLine(date1.ToString("G", CultureInfo.CreateSpecificCulture("nl-BE"))); // Displays 10/04/2008 6:30:00Back to table The Month ("M", "m") Format Specifier

Defines the string that separates the year, month, and day components of a date. Defines the string that separates the hour, minute, and second components of a time. Defines the string that indicates times from midnight to before noon in a 12hour clock. Defines the string that indicates times from noon to before midnight in a 12hour clock.

The following example uses the "G" format specifier to display a date and time value.

The "M" or "m" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.MonthDayPattern property. For example, the custom format string for the invariant culture is "MMMM dd".The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned string.

Property

Description

MonthDayPattern Defines the overall format of the result string. MonthNamesVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0);

Defines the localized month names that can appear in the result string.

The following example uses the "m" format specifier to display a date and time value.

Console.WriteLine(date1.ToString("m", CultureInfo.CreateSpecificCulture("en-us"))); // Displays April 10 Console.WriteLine(date1.ToString("m", CultureInfo.CreateSpecificCulture("ms-MY"))); // Displays 10 April Back to table The Round-trip ("O", "o") Format Specifier

The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using theDateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string. The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied. Strings that are passed to the Parse or ParseExact method must conform exactly to this custom format pattern, or a FormatException is thrown. When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture. The following example uses the "o" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); DateTimeOffset dateOffset = new DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOffset(date1)); Console.WriteLine(date1.ToString("o")); // Displays 2008-04-10T06:30:00.0000000 Console.WriteLine(dateOffset.ToString("o")); // Displays 2008-04-10T06:30:00.0000000-07:00The following example uses the "o" format specifier to create a formatted string, and then restores the original date and time value by calling a date and time Parse method.

VB C# C++ F# JScript

Copy // Round-trip DateTime values. DateTime originalDate, newDate; string dateString; // Round-trip a local time. originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 10, 6, 30, 0), DateTimeKind.Local); dateString = originalDate.ToString("o"); newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind); Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, newDate, newDate.Kind); // Round-trip a UTC time. originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 12, 9, 30, 0), DateTimeKind.Utc); dateString = originalDate.ToString("o"); newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind); Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, newDate, newDate.Kind); // Round-trip time in an unspecified time zone. originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 13, 12, 30, 0), DateTimeKind.Unspecified); dateString = originalDate.ToString("o"); newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind); Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, newDate, newDate.Kind);// Round-trip a DateTimeOffset value. DateTimeOffset originalDTO = new DateTimeOffset(2008, 4, 12, 9, 30, 0, new TimeSpan(-8, 0, 0)); dateString = originalDTO.ToString("o"); DateTimeOffset newDTO = DateTimeOffset.Parse(dateString, null, DateTimeStyles.RoundtripKind); Console.WriteLine("Round-tripped {0} to {1}.", originalDTO, newDTO); // The example displays the following output: // Round-tripped 4/10/2008 6:30:00 AM Local to 4/10/2008 6:30:00 AM Local. // Round-tripped 4/12/2008 9:30:00 AM Utc to 4/12/2008 9:30:00 AM Utc. // Round-tripped 4/13/2008 12:30:00 PM Unspecified to 4/13/2008 12:30:00 PM Unspecified. // Round-tripped 4/12/2008 9:30:00 AM -08:00 to 4/12/2008 9:30:00 AM -08:00. Back to table The RFC1123 ("R", "r") Format Specifier

The "R" or "r" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.RFC1123Pattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.The result string is affected by the following properties of the DateTimeFormatInfo object returned by the DateTimeFormatInfo.InvariantInfo property that represents the invariant culture.

Property RFC1123Pattern AbbreviatedDayNames

Description Defines the format of the result string. Defines the abbreviated day names that can appear in the result string.

AbbreviatedMonthNames Defines the abbreviated month names that can appear in the result

string.Although the RFC 1123 standard expresses a time as Coordinated Universal Time (UTC), the formatting operation does not modify the value of the DateTime or DateTimeOffsetobject that is being formatted. Therefore, the application must convert the date and time value to UTC before it performs the formatting operation. To perform this conversion,DateTime values can call the DateTime.ToUniversalTime method, and DateTimeOffset values can call the ToUniversalTime method. The following example uses the "r" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); DateTimeOffset dateOffset = new DateTimeOffset(date1, TimeZoneInfo.Local.GetUtcOffset(date1)); Console.WriteLine(date1.ToUniversalTime().ToString("r")); // Displays Thu, 10 Apr 2008 13:30:00 GMT Console.WriteLine(dateOffset.ToUniversalTime().ToString("r")); // Displays Thu, 10 Apr 2008 13:30:00 GMTBack to table The Sortable ("s") Format Specifier

The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture. The following example uses the "s" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("s")); // Displays 2008-04-10T06:30:00Back to table The Short Time ("t") Format Specifier

The "t" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.ShortTimePattern property. For example, the custom format string for the invariant culture is "HH:mm".The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by the DateTimeFormatInfo.ShortTimePattern property of some cultures may not make use of all properties.

Property

Description

ShortTimePattern Defines the format of the time component of the result string. TimeSeparator AMDesignator PMDesignatorVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("t", CultureInfo.CreateSpecificCulture("en-us"))); // Displays 6:30 AM Console.WriteLine(date1.ToString("t", CultureInfo.CreateSpecificCulture("es-ES"))); // Displays 6:30Back to table The Long Time ("T") Format Specifier

Defines the string that separates the hour, minute, and second components of a time. Defines the string that indicates times from midnight to before noon in a 12hour clock. Defines the string that indicates times from noon to before midnight in a 12hour clock.

The following example uses the "t" format specifier to display a date and time value.

The "T" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.LongTimePattern property. For example, the custom format string for the invariant culture is "HH:mm:ss".The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by theDateTimeFormatInfo.LongTimePattern property of some cultures may not make use of all properties.

Property

Description

LongTimePattern Defines the format of the time component of the result string. TimeSeparator Defines the string that separates the hour, minute, and second components of a time.

AMDesignator PMDesignatorVB C# C++ F# JScript Copy

Defines the string that indicates times from midnight to before noon in a 12hour clock. Defines the string that indicates times from noon to before midnight in a 12hour clock.

The following example uses the "T" format specifier to display a date and time value.

DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("T", CultureInfo.CreateSpecificCulture("en-us"))); // Displays 6:30:00 AM Console.WriteLine(date1.ToString("T", CultureInfo.CreateSpecificCulture("es-ES"))); // Displays 6:30:00Back to table The Universal Sortable ("u") Format Specifier

The "u" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.Although the result string should express a time as Coordinated Universal Time (UTC), no conversion of the original DateTime or DateTimeOffset value is performed during the formatting operation. Therefore, the application must convert the date and time value to UTC before formatting it. To perform this conversion, DateTime values can call theDateTime.ToUniversalTime method, and DateTimeOffset values can call the ToUniversalTime method The following example uses the "u" format specifier to display a date and time value.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToUniversalTime().ToString("u")); // Displays 2008-04-10 13:30:00ZBack to table The Universal Full ("U") Format Specifier

The "U" standard format specifier represents a custom date and time format string that is defined by a specified culture's DateTimeFormatInfo.FullDateTimePattern property. The pattern is the same as the "F" pattern. However, the DateTime value is automatically converted to UTC before it is formatted.The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by theFullDateTimePattern property of some cultures may not make use of all properties.

Property

Description

FullDateTimePattern Defines the overall format of the result string. DayNames MonthNames TimeSeparator AMDesignator PMDesignator Defines the localized day names that can appear in the result string. Defines the localized month names that can appear in the result string. Defines the string that separates the hour, minute, and second components of a time. Defines the string that indicates times from midnight to before noon in a 12hour clock. Defines the string that indicates times from noon to before midnight in a 12hour clock.

The "U" format specifier is not supported by the DateTimeOffset type and throws a FormatException if it is used to format a DateTimeOffset value. The following example uses the "U" format specifier to display a date and time value.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("en-US"))); // Displays Thursday, April 10, 2008 1:30:00 PM Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("sv-FI"))); // Displays den 10 april 2008 13:30:00Back to table The Year Month ("Y", "y") Format Specifier

The "Y" or "y" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.YearMonthPattern property of a specified culture. For example, the custom format string for the invariant culture is "yyyy MMMM".The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned string.

Property

Description

YearMonthPattern Defines the overall format of the result string. MonthNamesVB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 4, 10, 6, 30, 0); Console.WriteLine(date1.ToString("Y", CultureInfo.CreateSpecificCulture("en-US"))); // Displays April, 2008 Console.WriteLine(date1.ToString("y", CultureInfo.CreateSpecificCulture("af-ZA"))); // Displays April 2008Back to table To customize the format of date or time you can pass appropriate format string to ToString function. Different types of Time formats that are commonly used in ASP.Net 2.0 are: 13:39:21.0363750 1:39 PM 13:39 21 PM 01:39 21 PM 1339

Defines the localized month names that can appear in the result string.

The following example uses the "y" format specifier to display a date and time value.

DateTime Format Examples:You can see the live samples and examples of C# DateTime format from the following links: Time Formats using ToString Function

Date Formats using ToString Function Convert String to DateTime DateTime Parse and ParseExact using IFormatProviderC# Functions to format the server Time String C# Time Formats: C# Code Example 1:

Response.Write(DateTime.Now.TimeOfDay);Output: 13:39:21.0363750

C# Code Example 2:

Response.Write(DateTime.Now.ToShortTimeString());Output: 1:39 PM

C# Code Example 3:

Response.Write(DateTime.Now.ToString("HH:mm ss tt"));Output: 13:39 21 PM Note: To format the time in 24H format you can use the capital HH to display the hours, mm to display the minutes, ss to display theseconds and tt for AM/PM.

C# Code Example 4:

Response.Write(DateTime.Now.ToString("hh:mm ss tt"));Output: 01:39 21 PM Note: To format the time into short string type, you can use the lower case hh to display the hours.

C# Code Example 5:

Response.Write(DateTime.Now.ToString("HHmm"));Output: 1339 Note: To display the time in hours format, just use HHmm without separators.

.NET Framework 4 Other Versions

Represents an instant in time, typically expressed as a date and time of day.Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

VB C# C++ F# JScript Copy [SerializableAttribute] public struct DateTime : IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable The DateTime type exposes the following members.Constructors

Name DateTime(Int64) DateTime(Int64, DateTimeKind) DateTime(Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar) DateTime(Int32, Int32, Int32, Int32, Int32, Int32, Int32, Calendar, DateTimeKind)Top Properties

Description Initializes a new instance of the DateTime structure to a specified number of ticks. Initializes a new instance of the DateTime structure to a specified number of ticks and to Coordinated Universal Time (UTC) or local time. Initializes a new instance of the DateTime structure to the specified year, month, and day. Initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and Coordinated Universal Time (UTC) or local time. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second for the specified calendar. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified calendar. Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.

Name Date Day

Description Gets the date component of this instance. Gets the day of the month represented by this instance.

DayOfWeek Gets the day of the week represented by this instance. DayOfYear Gets the day of the year represented by this instance. Hour Kind Gets the hour component of the date represented by this instance. Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.

Millisecond Gets the milliseconds component of the date represented by this instance. Minute Month Now Second Ticks Today UtcNow YearTop Methods

Gets the minute component of the date represented by this instance. Gets the month component of the date represented by this instance. Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time. Gets the seconds component of the date represented by this instance. Gets the number of ticks that represent the date and time of this instance. Gets the current date. Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC). Gets the year component of the date represented by this instance.

TimeOfDay Gets the time of day for this instance.

Name Add AddDays AddHours AddMilliseconds AddMinutes AddMonths AddSeconds AddTicks AddYears Compare

Description Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance. Returns a new DateTime that adds the specified number of days to the value of this instance. Returns a new DateTime that adds the specified number of hours to the value of this instance. Returns a new DateTime that adds the specified number of milliseconds to the value of this instance. Returns a new DateTime that adds the specified number of minutes to the value of this instance. Returns a new DateTime that adds the specified number of months to the value of this instance. Returns a new DateTime that adds the specified number of seconds to the value of this instance. Returns a new DateTime that adds the specified number of ticks to the value of this instance. Returns a new DateTime that adds the specified number of years to the value of this instance. Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

CompareTo(DateTime)

CompareTo(Object) DaysInMonth Equals(DateTime) Equals(Object) Equals(DateTime, DateTime) Finalize FromBinary FromFileTime FromFileTimeUtc FromOADate GetDateTimeFormats()

Compares the value of this instance to a specified object that contains a specified DateTime value, and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value. Returns the number of days in the specified month and year. Returns a value indicating whether this instance is equal to the specified DateTime instance. Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType.Equals(Object).) Returns a value indicating whether two instances of DateTime are equal. Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Deserializes a 64-bit binary value and recreates an original serialized DateTime object. Converts the specified Windows file time to an equivalent local time. Converts the specified Windows file time to an equivalent UTC time. Returns a DateTime equivalent to the specified OLE Automation Date. Converts the value of this instance to all the string representations supported by the standard date and time format specifiers.

Converts the value of this instance to all the string GetDateTimeFormats(Ch representations supported by the specified standard date and ar) time format specifier. Converts the value of this instance to all the string GetDateTimeFormats(IF representations supported by the standard date and time format ormatProvider) specifiers and the specified culture-specific formatting information. Converts the value of this instance to all the string GetDateTimeFormats(Ch representations supported by the specified standard date and ar, IFormatProvider) time format specifier and culture-specific formatting information. GetHashCode GetType GetTypeCode IsDaylightSavingTime IsLeapYear MemberwiseClone Parse(String) Returns the hash code for this instance. (Overrides ValueType.GetHashCode().) Gets the Type of the current instance. (Inherited from Object.) Returns the TypeCode for value type DateTime. Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone. Returns an indication whether the specified year is a leap year. Creates a shallow copy of the current Object. (Inherited from Object.) Converts the specified string representation of a date and time

to its DateTime equivalent. Parse(String, IFormatProvider) Parse(String, IFormatProvider, DateTimeStyles) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information. Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style.

Converts the specified string representation of a date and time ParseExact(String, to its DateTime equivalent using the specified format and String, IFormatProvider) culture-specific format information. The format of the string representation must match the specified format exactly. Converts the specified string representation of a date and time ParseExact(String, to its DateTime equivalent using the specified format, cultureString, IFormatProvider, specific format information, and style. The format of the string DateTimeStyles) representation must match the specified format exactly or an exception is thrown. Converts the specified string representation of a date and time ParseExact(String, String to its DateTime equivalent using the specified array of formats, [], IFormatProvider, culture-specific format information, and style. The format of DateTimeStyles) the string representation must match at least one of the specified formats exactly or an exception is thrown. SpecifyKind Subtract(DateTime) Subtract(TimeSpan) ToBinary ToFileTime ToFileTimeUtc ToLocalTime ToLongDateString ToLongTimeString ToOADate ToShortDateString ToShortTimeString ToString() Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value. Subtracts the specified date and time from this instance. Subtracts the specified duration from this instance. Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTimeobject. Converts the value of the current DateTime object to a Windows file time. Converts the value of the current DateTime object to a Windows file time. Converts the value of the current DateTime object to local time. Converts the value of the current DateTime object to its equivalent long date string representation. Converts the value of the current DateTime object to its equivalent long time string representation. Converts the value of this instance to the equivalent OLE Automation date. Converts the value of the current DateTime object to its equivalent short date string representation. Converts the value of the current DateTime object to its equivalent short time string representation. Converts the value of the current DateTime object to its

equivalent string representation. (OverridesValueType.ToString().) Converts the value of the current DateTime object to its ToString(IFormatProvide equivalent string representation using the specified culturer) specific format information. ToString(String) ToString(String, IFormatProvider) ToUniversalTime TryParse(String, DateTime) TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the value of the current DateTime object to its equivalent string representation using the specified format. Converts the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information. Converts the value of the current DateTime object to Coordinated Universal Time (UTC). Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded. Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

Converts the specified string representation of a date and time TryParseExact(String, to its DateTime equivalent using the specified format, cultureString, IFormatProvider, specific format information, and style. The format of the string DateTimeStyles, representation must match the specified format exactly. The DateTime) method returns a value that indicates whether the conversion succeeded. TryParseExact(String, St ring[], IFormatProvider, DateTimeStyles, DateTime)Top Operators

Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match at least one of the specified formats exactly. The method returns a value that indicates whether the conversion succeeded.

Name Addition Equality GreaterThan GreaterThanOrEqual Inequality

Description Adds a specified time interval to a specified date and time, yielding a new date and time. Determines whether two specified instances of DateTime are equal. Determines whether one specified DateTime is greater than another specified DateTime. Determines whether one specified DateTime is greater than or equal to another specified DateTime. Determines whether two specified instances of DateTime are

not equal. LessThan LessThanOrEqual Subtraction(DateTime, DateTime) Subtraction(DateTime, TimeSpan)Top Fields

Determines whether one specified DateTime is less than another specified DateTime. Determines whether one specified DateTime is less than or equal to another specified DateTime. Subtracts a specified date and time from another specified date and time and returns a time interval. Subtracts a specified time interval from a specified date and time and returns a new date and time.

Name Description MaxValue Represents the largest possible value of DateTime. This field is read-only. MinValue Represents the smallest possible value of DateTime. This field is read-only.Top Explicit

Interface Implementations

Name IConvertible.ToBoolean IConvertible.ToByte IConvertible.ToChar IConvertible.ToDateTime IConvertible.ToDecimal IConvertible.ToDouble IConvertible.ToInt16 IConvertible.ToInt32 IConvertible.ToInt64 IConvertible.ToSByte IConvertible.ToSingle IConvertible.ToType IConvertible.ToUInt16 IConvertible.ToUInt32 IConvertible.ToUInt64 ISerializable.GetObjectDataTop

Description Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. Returns the current DateTime object. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. Converts the current DateTime object to an object of a specified type. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Infrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException. Populates a SerializationInfo object with the data needed to serialize the current DateTime object.

Remarks

The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.).Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in theGregorianCalendar calendar (excluding ticks that would be added by leap seconds). For example, a ticks value of 31241376000000000L represents the date, Friday, January 01, 0100 12:00:00 midnight. A DateTime value is always expressed in the context of an explicit or default calendar.

Note If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the TimeSpan.TicksPerDay,TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.Ticks PerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. For example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTime value, you can use the expression dateValue.Second + nTicks/Timespan.TicksPerSecond.Instantiating a DateTime Object You can create a new DateTime value in any of the following ways: By calling any of the overloads of the DateTime constructor that allow you to specify specific elements of the date and time value (such as the year, month, and day, or the number of ticks). The following statement illustrates a call to one of the DateTime constructors to create a date with a specific year, month, day, hour, minute, and second.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52); By using any compiler-specific syntax for declaring date and time values. For example, the following Visual Basic statement initializes a new DateTime value.

VB C# C++ F# JScript Copy

This language is not supported or no code example is available. By assigning the DateTime object a date and time value returned by a property or method. The following example assigns the current date and time, the current Coordinated Universal Time (UTC) date and time, and the current date to three new DateTime variables. VB C# C++

F# JScript Copy DateTime date1 = DateTime.Now; DateTime date2 = DateTime.UtcNow; DateTime date3 = DateTime.Today;

By parsing the string representation of a date and time value.

The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. The following example uses the Parse method to parse a string and convert it to a DateTime value.

VB C# C++ F# JScript Copy string dateString = "5/1/2008 8:30:52 AM"; DateTime date1 = DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture);Note that the TryParse and TryParseExact methods indicate whether a particular string contains a valid representation of a DateTime value in addition to performing the conversion.

By calling the DateTime structure's implicit default constructor. (For details on the implicitdefault constructor of a value type, see Value Types (C# Reference).) An approximate equivalent, for compilers that support it, is declaring a DateTime value without explicitly assigning a date and time to it. The following example illustrates a call to the DateTime implicit default constructor in C# and Visual Basic, as well as a DateTime variable declaration with no assignment in Visual Basic.

VB C# C++ F# JScript Copy DateTime dat1 = new DateTime(); // The following method call displays 1/1/0001 12:00:00 AM. Console.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture)); // The following method call displays True. Console.WriteLine(dat1.Equals(DateTime.MinValue));

DateTime Values and Their String Representations Internally, all DateTime values are represented as the number of ticks (the number of 100nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a DateTimevalue is the result of a formatting operation. Formatting is the process of converting a value to its string representation. Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, theDateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of its ToString method. The default DateTime.ToString() method returns the string

representation of a date and time value using the current culture's short date and long time pattern. The following example uses the defaultDateTime.ToString() method to display the date and time using the short date and long time pattern for the en-US culture, the current culture on the computer on which the example was run.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0); Console.WriteLine(date1.ToString()); // For en-US culture, displays 3/1/2008 7:00:00 AMThe DateTime.ToString(IFormatProvider) method returns the string representation of a date and time value using the short date and long time pattern of a specific culture. The following example uses the DateTime.ToString(IFormatProvider) method to display the date and time using the short date and long time pattern for the fr-FR culture.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0); Console.WriteLine(date1.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("frFR"))); // Displays 01/03/2008 07:00:00The DateTime.ToString(String) method returns the string representation of the date and time in a format defined by a standard or custom format specifier and using the formatting conventions of the current culture. The following example uses the DateTime.ToString(String) method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0); Console.WriteLine(date1.ToString("F")); // Displays Saturday, March 01, 2008 7:00:00 AMThe DateTime.ToString(String, IFormatProvider) method returns the string representation of the date and time in a format defined by a specific format specifier and using the formatting conventions of a specific culture. The following example uses the DateTime.ToString(String, IFormatProvider) method to display the full date and time pattern for the fr-FR culture.

VB C# C++ F# JScript Copy DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);

Console.WriteLine(date1.ToString("F", new System.Globalization.CultureInfo("fr-FR"))); // Displays samedi 1 mars 2008 07:00:00

Version Considerations Prior to the .NET Framework version 2.0, the DateTime structure contains a 64-bit field composed of an unused 2-bit field concatenated with a private Ticks field, which is a 62-bit unsigned field that contains the number of ticks that represent the date and time. The value of the Ticks field can be obtained with the Ticks property. Starting with the .NET Framework 2.0, the DateTime structure contains a 64-bit field composed of a private Kind field concatenated with the Ticks field. The Kind field is a 2-bit field that indicates whether the DateTime structure represents a local time, a Coordinated Universal Time (UTC), or the time in an unspecified time zone. The Kind field is used when performing time conversions between time zones, but not for time comparisons or arithmetic. The value of the Kind field can be obtained with the Kind property.

Note An alternative to the DateTime structure for working with date and time values in particular time zones is the DateTimeOffset structure. The DateTimeOffset structure stores date and time information in a private DateTime field and the number of minutes by which that date and time differs from UTC in a private Int16 field. This makes it possible for a DateTimeOffset value to reflect the time in a particular time zone, whereas a DateTime value can unambiguously reflect only UTC and the local time zone's time. For a discussion about when to use the DateTime structure or the DateTimeOffset structure when working with date and time values, see Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo.DateTime Values Descriptions of time values in the DateTime type are often expressed using the Coordinated Universal Time (UTC) standard, which is the internationally recognized name for Greenwich Mean Time (GMT). Coordinated Universal Time is the time as measured at zero degrees longitude, the UTC origin point. Daylight saving time is not applicable to UTC. Local time is relative to a particular time zone. A time zone is associated with a time zone offset, which is the displacement of the time zone measured in hours from the UTC origin point. In addition, local time is optionally affected by daylight saving time, which adds or subtracts an hour from the length of a day. Consequently, local time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. The time zone offset at the UTC origin point is zero. UTC time is suitable for calculations, comparisons, and storing dates and time in files. Local time is appropriate for display in user interfaces of desktop applications. Time zone-aware applications (such as many Web applications) also need to work with a number of other time zones. If the Kind property of a DateTime object is DateTimeKind.Unspecified, it is unspecified whether the time represented is local time, UTC time, or a time in some other time zone. DateTime Operations A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation. Conversion operations between time zones (such as between UTC and local time, or between one time zone and another) take daylight saving time into account, but arithmetic and comparison operations do not. The DateTime structure itself offers limited support for converting from one time zone to another. You can use the ToLocalTime method to convert UTC to local time, or you can use the ToUniversalTime method to convert from local time to UTC. However, a full set of time zone conversion methods is available in the TimeZoneInfo class. Using these methods, you can convert the time in any one of the world's time zones to the time in any other time zone.

Calculations and comparisons of DateTime objects are meaningful only if the objects represent times in the same time zone. You can use a TimeZoneInfo object to represent aDateTime value's time zone, although the two are loosely coupled. (That is, a DateTime object does not have a property that returns an object that represents that date and time value's time zone other than the Kind property.) For this reason, in a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a DateTime object was created. For example, you could use a structure that wraps both the DateTime value and the TimeZoneInfo object that represents the DateTimevalue's time zone. For details on using UTC in calculations and comparisons with DateTime values, see Performing Arithmetic Operations with Dates and Times. Each DateTime member implicitly uses the Gregorian calendar to perform its operation, with the exception of constructors that specify a calendar, and methods with a parameter derived from IFormatProvider, such as System.Globalization.DateTimeFormatInfo, that implicitly specifies a calendar. Operations by members of the DateTime type take into account details such as leap years and the number of days in a month. DateTime vs. TimeSpan The DateTime and TimeSpan value types differ in that a DateTime represents an instant in time whereas a TimeSpan represents a time interval. This means, for example, that you can subtract one instance of DateTime from another to obtain a TimeSpan object that represents the time interval between them. Or you could add a positive TimeSpan to the current DateTime to obtain a DateTime value that represents a future date. You can add or subtract a time interval from a DateTime object. Time intervals can be negative or positive, can be expressed in units such as ticks or seconds, or can be expressed as a TimeSpan object. COM Interop Considerations A DateTime value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. However, a DateTime value that specifies only a time does not round-trip as you might expect. If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. at 3:00 P.M., instead of January, 1, 0001 C.E. at 3:00 P.M. This happens because the .NET Framework and COM assume a default date when only a time is specified. However, the COM system assumes a base date of December 30, 1899 C.E. while the .NET Framework assumes a base date of January, 1, 0001 C.E. When only a time is passed from the .NET Framework to COM, special processing is performed that converts the time to the format used by COM. When only a time is passed from COM to the .NET Framework, no special processing is performed because that would corrupt legitimate dates and times on or before December 30, 1899. This also means if a date starts its round-trip from COM, the .NET Framework and COM preserve the date. The behavior of the .NET Framework and COM means that if your application round-trips a DateTime that only specifies a time, your application must remember to modify or ignore the erroneous date from the final DateTime object. Examples

The following example demonstrates how to compare roughly equivalent DateTime values, accepting a small margin of difference when declaring them equal.VB C# C++ F#

JScript Copy using System;class DateTimeTester { static bool RoughlyEquals(DateTime time, DateTime timeWithWindow, int windowInSeconds, int frequencyInSeconds) { long delta = (long)((TimeSpan)(timeWithWindow - time)).TotalSeconds % frequencyInSeconds; delta = delta > windowInSeconds ? frequencyInSeconds - delta : delta; return Math.Abs(delta) < windowInSeconds; } public static void Main() { int window = 10; int freq = 60 * 60 * 2; // 2 hours; DateTime d1 = DateTime.Now; DateTime DateTime DateTime DateTime DateTime DateTime DateTime DateTime d2 d3 d4 d5 d6 d7 d8 d9 = = = = = = = = d1.AddSeconds(2 * window); d1.AddSeconds(-2 * window); d1.AddSeconds(window / 2); d1.AddSeconds(-window / 2); (d1.AddHours(2)).AddSeconds(2 * window); (d1.AddHours(2)).AddSeconds(-2 * window); (d1.AddHours(2)).AddSeconds(window / 2); (d1.AddHours(2)).AddSeconds(-window / 2); d1, window, freq)); d2, window, freq)); d3, window, freq)); d4, window, freq)); d5, window, freq)); d6, window, freq)); d7, window, freq)); d8, window, freq)); d9, window, freq));

Console.WriteLine("d1 ({0}) ~= d1 ({1}): {2}", d1, d1, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d2 ({1}): {2}", d1, d2, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d3 ({1}): {2}", d1, d3, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d4 ({1}): {2}", d1, d4, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d5 ({1}): {2}", d1, d5, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d6 ({1}): {2}", d1, d6, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d7 ({1}): {2}", d1, d7, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d8 ({1}): {2}", d1, d8, RoughlyEquals(d1, Console.WriteLine("d1 ({0}) ~= d9 ({1}): {2}", d1, d9, RoughlyEquals(d1, }

} // The example displays output similar to the following: // d1 (1/28/2010 9:01:26 PM) ~= d1 (1/28/2010 9:01:26 // d1 (1/28/2010 9:01:26 PM) ~= d2 (1/28/2010 9:01:46 // d1 (1/28/2010 9:01:26 PM) ~= d3 (1/28/2010 9:01:06 // d1 (1/28/2010 9:01:26 PM) ~= d4 (1/28/2010 9:01:31

PM): PM): PM): PM):

True False False True

// // // // //

d1 d1 d1 d1 d1

(1/28/2010 (1/28/2010 (1/28/2010 (1/28/2010 (1/28/2010

9:01:26 9:01:26 9:01:26 9:01:26 9:01:26

PM) PM) PM) PM) PM)

~= ~= ~= ~= ~=

d5 d6 d7 d8 d9

(1/28/2010 (1/28/2010 (1/28/2010 (1/28/2010 (1/28/2010

9:01:21 PM): True 11:01:46 PM): False 11:01:06 PM): False 11:01:31 PM): True 11:01:21 PM): True

Version Information

.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

Custom Date and Time Format Strings

.NET Framework 4

Other Versions

Updated: July 2010A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation . It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time. A custom format string consists of one or more custom date and time format specifiers. Any string that is not a standard date and time format string is interpreted as a custom date and time format string.

Note Custom date and time format strings can be used with both DateTime and DateTimeOffset values. In formatting operations, custom date and time format strings can be used either with the ToString method of a date and time instance or with a method that supports composite formatting. The following example illustrates both uses.VB C# C++ F# JScript Copy DateTime thisDate1 = new DateTime(2011, 6, 10); Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");DateTimeOffset thisDate2 = new DateTimeOffset(2011, 6, 10, 15, 24, 16, TimeSpan.Zero); Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", thisDate2);

// The example displays the following output: // Today is June 10, 2011. // The current date and time: 06/10/11 15:24:16 +00:00 In parsing operations, custom date and time format strings can be used with the DateTime.ParseExact, DateTime.TryParseExact, DateTimeOffset.ParseExact, andDateTimeOffset.TryParseExact methods. These methods require that an input string conform exactly to a particular pattern for the parse operation to succeed. The following example illustrates a call to the DateTimeOffset.ParseExact(String, String, IFormatProvider) method to parse a date that must include a day, a month, and a two-digit year.

VB C# C++ F# JScript Copy using System; using System.Globalization;public class Example { public static void Main() { string[] dateValues = { "30-12-2011", "12-30-2011", "30-12-11", "12-30-11" }; string pattern = "MM-dd-yy"; DateTime parsedDate; foreach (var dateValue in dateValues) { if (DateTime.TryParseExact(dateValue, pattern, null, DateTimeStyles.None, out parsedDate)) Console.WriteLine("Converted '{0}' to {1:d}.", dateValue, parsedDate); else Console.WriteLine("Unable to convert '{0}' to a date and time.", dateValue); } } } // The example displays the following output: // Unable to convert '30-12-2011' to a date and time. // Unable to convert '12-30-2011' to a date and time. // Unable to convert '30-12-11' to a date and time. // Converted '12-30-11' to 12/30/2011. The following table describes the custom date and time format specifiers and displays a result string produced by each format specifier. If a particular format specifier produces a localized result string, the example also notes the culture to which the result string applies. See the Notes section for additional information about using custom date and time format strings.

Format specifier

Description

Examples

"d"

The day of the month, from 1 through 31. 6/1/2009 1:45:30 PM -> 1 More information: The "d" Custom 6/15/2009 1:45:30 PM -> 15 Format Specifier.

"dd"

The day of the month, from 01 through 31. 6/1/2009 1:45:30 PM -> 01 More information: The "dd" Custom 6/15/2009 1:45:30 PM -> 15 Format Specifier. The abbreviated name of the day of 6/15/2009 1:45:30 PM -> Mon (en-US) the week. 6/15/2009 1:45:30 PM -> (ru-RU) More information: The "ddd" 6/15/2009 1:45:30 PM -> lun. (fr-FR) Custom Format Specifier. The full name of the day of the week. More information: The "dddd" Custom Format Specifier. 6/15/2009 1:45:30 PM -> Monday (en-US) 6/15/2009 1:45:30 PM -> (ruRU) 6/15/2009 1:45:30 PM -> lundi (fr-FR)

"ddd"

"dddd"

"f"

The tenths of a second in a date and time value. 6/15/2009 13:45:30.617 -> 6 More information: The "f" Custom 6/15/2009 13:45:30.050 -> 0 Format Specifier. The hundredths of a second in a date and time value. 6/15/2009 13:45:30.617 -> 61 More information: The "ff" Custom 6/15/2009 13:45:30.005 -> 00 Format Specifier. The milliseconds in a date and time value. 6/15/2009 13:45:30.617 -> 617 More information: The "fff" Custom 6/15/2009 13:45:30.0005 -> 000 Format Specifier. The ten thousandths of a second in a date and time value. 6/15/2009 13:45:30.6175 -> 6175 More information: The "ffff" 6/15/2009 13:45:30.00005 -> 0000 Custom Format Specifier. The hundred thousandths of a second in a date and time value. More information: The "fffff" Custom Format Specifier. 6/15/2009 13:45:30.61754 -> 61754 6/15/2009 13:45:30.000005 -> 00000

"ff"

"fff"

"ffff"

"fffff"

"ffffff"

The millionths of a second in a date and time value. 6/15/2009 13:45:30.617542 -> 617542 More information: The "ffffff" 6/15/2009 13:45:30.0000005 -> 000000 Custom Format Specifier. The ten millionths of a second in a date and time value. More information: The "fffffff" Custom Format Specifier. 6/15/2009 13:45:30.6175425 -> 6175425 6/15/2009 13:45:30.0001150 -> 0001150

"fffffff"

"F" "FF"

If non-zero, the tenths of a second in a date and time value. 6/15/2009 13:45:30.617 -> 6 More information: The "F" Custom 6/15/2009 13:45:30.050 -> (no output) Format Specifier. If non-zero, the hundredths of a second in a date and time value. More information: The "FF" 6/15/2009 13:45:30.617 -> 61 6/15/2009 13:45:30.005 -> (no output)

Custom Format Specifier. "FFF" If non-zero, the milliseconds in a date and time value. More information: The "FFF" Custom Format Specifier. 6/15/2009 13:45:30.617 -> 617 6/15/2009 13:45:30.0005 -> (no output)

"FFFF"

If non-zero, the ten thousandths of a second in a date and time value. 6/1/2009 13:45:30.5275 -> 5275 More information: The "FFFF" 6/15/2009 13:45:30.00005 -> (no output) Custom Format Specifier. If non-zero, the hundred thousandths of a second in a date and time value. More information: The "FFFFF" Custom Format Specifier. If non-zero, the millionths of a second in a date and time value. More information: The "FFFFFF" Custom Format Specifier. 6/15/2009 13:45:30.61754 -> 61754 6/15/2009 13:45:30.000005 -> (no output)

"FFFFF"

"FFFFFF"

6/15/2009 13:45:30.617542 -> 617542 6/15/2009 13:45:30.0000005 -> (no output)

"FFFFFFF"

If non-zero, the ten millionths of a second in a date and time value. 6/15/2009 13:45:30.6175425 -> 6175425 More information: The "FFFFFFF" 6/15/2009 13:45:30.0001150 -> 000115 Custom Format Specifier. The period or era. More information: The "g" or "gg" Custom Format Specifier. 6/15/2009 1:45:30 PM -> A.D.

"g", "gg"

"h"

The hour, using a 12-hour clock from 1 to 12. 6/15/2009 1:45:30 AM -> 1 More information: The "h" Custom 6/15/2009 1:45:30 PM -> 1 Format Specifier. The hour, using a 12-hour clock from 01 to 12. 6/15/2009 1:45:30 AM -> 01 More information: The "hh" Custom 6/15/2009 1:45:30 PM -> 01 Format Specifier. The hour, using a 24-hour clock from 0 to 23. 6/15/2009 1:45:30 AM -> 1 More information: The "H" Custom 6/15/2009 1:45:30 PM -> 13 Format Specifier. The hour, using a 24-hour clock from 00 to 23. More information: The "HH" Custom Format Specifier. 6/15/2009 1:45:30 AM -> 01 6/15/2009 1:45:30 PM -> 13

"hh"

"H"

"HH" "K"

Time zone information. With DateTime values: More