System.Globalization.DateTimeFormatInfo Class

Provides culture-specific information about the format of date and time values.

See Also: DateTimeFormatInfo Members

Syntax

[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider

Remarks

The properties of the System.Globalization.DateTimeFormatInfo class contain culture-specific information for formatting or parsing date and time values such as the following:

In this section:

Instantiating a DateTimeFormatInfo object

A System.Globalization.DateTimeFormatInfo object can represent the formatting conventions of the invariant culture, a specific culture, a neutral culture, or the current culture. This section discusses how to instantiate each type of System.Globalization.DateTimeFormatInfo object.

Instantiating a DateTimeFormatInfo object for the invariant culture

The invariant culture represents a culture that is culture-insensitive. It is based on the English language, but not on any specific English-speaking country/region. Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. You can instantiate a System.Globalization.DateTimeFormatInfo object that represents the formatting conventions of the invariant culture in the following ways:

The following example uses each of these methods to instantiate a System.Globalization.DateTimeFormatInfo object that represents the invariant culture. It then indicates whether the object is read-only.

code reference: System.Globalization.DateTimeFormatInfo.Class#1

Instantiating a DateTimeFormatInfo object for a specific culture

A specific culture represents a language that is spoken in a particular country/region. For example, en-US is a specific culture that represents the English language spoken in the United States, and en-CA is a specific culture that represents the English language spoken in Canada. You can instantiate a System.Globalization.DateTimeFormatInfo object that represents the formatting conventions of a specific culture in the following ways:

The following example illustrates each of these ways to instantiate a System.Globalization.DateTimeFormatInfo object and indicates whether the resulting object is read-only.

code reference: System.Globalization.DateTimeFormatInfo.Class#3

Instantiating a DateTimeFormatInfo object for a neutral culture

A neutral culture represents a culture or language that is independent of a country/region; it is typically the parent of one or more specific cultures. For example, Fr is a neutral culture for the French language and the parent of the fr-FR culture. You can instantiate a System.Globalization.DateTimeFormatInfo object that represents the formatting conventions of a neutral culture in the same ways that you create a System.Globalization.DateTimeFormatInfo object that represents the formatting conventions of a specific culture. In addition, you can retrieve a neutral culture's System.Globalization.DateTimeFormatInfo object by retrieving a neutral culture from a specific culture's CultureInfo.Parent property and retrieving the System.Globalization.DateTimeFormatInfo object returned by its CultureInfo.DateTimeFormat property. Unless the parent culture represents the invariant culture, the returned System.Globalization.DateTimeFormatInfo object is read/write. The following example illustrates these ways of instantiating a System.Globalization.DateTimeFormatInfo object that represents a neutral culture.

code reference: System.Globalization.DateTimeFormatInfo.Class#2

Note:

In the .NET Framework versions 1.0 through net_v35_short, trying to retrieve a System.Globalization.DateTimeFormatInfo object that reflects the formatting conventions of a neutral culture throws a NotSupportedException exception.

However, a neutral culture lacks culture-specific formatting information, because it is independent of a specific country/region. Instead of populating the System.Globalization.DateTimeFormatInfo object with generic values, the .NET Framework returns a System.Globalization.DateTimeFormatInfo object that reflects the formatting conventions of a specific culture that is a child of the neutral culture. For example, the System.Globalization.DateTimeFormatInfo object for the neutral en culture reflects the formatting conventions of the en-US culture, and the System.Globalization.DateTimeFormatInfo object for the fr culture reflects the formatting conventions of the fr-FR culture.

You can use code like the following to determine which specific culture's formatting conventions a neutral culture represents. The example uses reflection to compare the System.Globalization.DateTimeFormatInfo properties of a neutral culture with the properties of a specific child culture. It considers two calendars to be equivalent if they are the same calendar type and, for Gregorian calendars, if their GregorianCalendar.CalendarType properties have identical values.

code reference: System.Globalization.DateTimeFormatInfo.Class#6

Instantiating a DateTimeFormatInfo object for the current culture

You can instantiate a System.Globalization.DateTimeFormatInfo object that represents the formatting conventions of the current culture in the following ways:

The following example uses each of these methods to instantiate a System.Globalization.DateTimeFormatInfo object that represents the formatting conventions of the current culture. It then indicates whether the object is read-only.

code reference: System.Globalization.DateTimeFormatInfo.Class#4

You can create a writable System.Globalization.DateTimeFormatInfo object that represents the conventions of the current thread culture in one of these ways:

The following example illustrates each way of instantiating a read/write System.Globalization.DateTimeFormatInfo object and displays the value of its DateTimeFormatInfo.IsReadOnly property.

code reference: System.Globalization.DateTimeFormatInfo.Class#7

In Windows, the user can override some of the System.Globalization.DateTimeFormatInfo property values used in formatting and parsing operations through the Region and Language application in Control Panel. For example, a user whose culture is English (United States) might choose to display long time values using a 24-hour clock (in the format HH:mm:ss) instead of the default 12-hour clock (in the format h:mm:ss tt). The System.Globalization.DateTimeFormatInfo objects retrieved in the ways discussed previously all reflect these user overrides. If this is undesirable, you can create a System.Globalization.NumberFormatInfo object that does not reflect user overrides (and is also read/write instead of read-only) by calling the CultureInfo.#ctor(string, bool) constructor and supplying a value of false for the useUserOverride argument. The following example illustrates this for a system whose current culture is English (United States) and whose long time pattern has been changed from the default of h:mm:ss tt to HH:mm:ss.

code reference: System.Globalization.DateTimeFormatInfo.Class#8

DateTimeFormatInfo and dynamic data

The culture-specific data for formatting date and time values provided by the System.Globalization.DateTimeFormatInfo class is dynamic, just like cultural data provided by the System.Globalization.CultureInfo class. You should not make any assumptions about the stability of values for System.Globalization.DateTimeFormatInfo objects that are associated with particular System.Globalization.CultureInfo objects. Only the data provided by the invariant culture and its associated System.Globalization.DateTimeFormatInfo object is stable. Other data can change between application sessions or even while your application is running. There are four major sources of change:

To minimize the possibility of inconsistent data, all user-overridable properties of a System.Globalization.DateTimeFormatInfo object are initialized when the object is created. There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic and the relevant values can change during object creation. However, this situation should be extremely rare.

You can control whether user overrides are reflected in System.Globalization.DateTimeFormatInfo objects that represent the same culture as the system culture. The following table lists the ways in which a System.Globalization.DateTimeFormatInfo object can be retrieved and indicates whether the resulting object reflects user overrides.

CultureInfo.CurrentCulture.DateTimeFormat property

Yes

DateTimeFormatInfo.CurrentInfo property

Yes

CultureInfo.CreateSpecificCulture(string) method

Yes

CultureInfo.GetCultureInfo(string) method

No

CultureInfo.#ctor(string) constructor

Yes

CultureInfo.#ctor(string, bool) constructor

Depends on value of useUserOverride parameter

Unless there is a compelling reason to do otherwise, you should respect user overrides when you use the System.Globalization.DateTimeFormatInfo object in client applications to format and parse user input or to display data. For server applications or unattended applications, you should not. However, if you are using the System.Globalization.DateTimeFormatInfo object either explicitly or implicitly to persist date and time data in string form, you should either use a System.Globalization.DateTimeFormatInfo object that reflects the formatting conventions of the invariant culture, or you should specify a custom date and time format string that you use regardless of culture.

Formatting dates and times

A System.Globalization.DateTimeFormatInfo object is used implicitly or explicitly in all date and time formatting operations. These include calls to the following methods:

All date and time formatting operations make use of an IFormatProvider implementation. The IFormatProvider interface includes a single method, IFormatProvider.GetFormat(Type). This callback method is passed a Type object that represents the type needed to provide formatting information. The method returns either an instance of that type or null if it cannot provide an instance of the type. The .NET Framework includes two IFormatProvider implementations for formatting dates and times:

If an IFormatProvider implementation is not provided to a formatting method explicitly, the System.Globalization.CultureInfo object returned by the CultureInfo.CurrentCulture property that represents the current thread culture is used.

The following example illustrates the relationship between the IFormatProvider interface and the System.Globalization.DateTimeFormatInfo class in formatting operations. It defines a custom IFormatProvider implementation whose IFormatProvider.GetFormat(Type) method displays the type of the object requested by the formatting operation. If it is requesting a System.Globalization.DateTimeFormatInfo object, the method provides the System.Globalization.DateTimeFormatInfo object for the current thread culture. As the output from the example shows, the decimal.ToString(IFormatProvider) method requests a System.Globalization.DateTimeFormatInfo object to provide formatting information, whereas the string.Format(IFormatProvider, string, Object[]) method requests System.Globalization.NumberFormatInfo and System.Globalization.DateTimeFormatInfo objects as well as an ICustomFormatter implementation.

code reference: System.Globalization.DateTimeFormatInfo.Class#9

Format strings and DateTimeFormatInfo properties

The System.Globalization.DateTimeFormatInfo object includes three kinds of properties that are used in formatting operations with date and time values:

The standard date and time format strings, such as "d", "D", "f", and "F", are aliases that correspond to particular System.Globalization.DateTimeFormatInfo format pattern properties. Most of the custom date and time format specifiers are related to strings or substrings that a formatting operation inserts into the result stream. The following table lists the standard and custom date and time format specifiers and their associated System.Globalization.DateTimeFormatInfo properties. For details about how to use these format specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Note that each standard format string corresponds to a System.Globalization.DateTimeFormatInfo property whose value is a custom date and time format string. The individual specifiers in this custom format string in turn correspond to other System.Globalization.DateTimeFormatInfo properties. The table lists only the System.Globalization.DateTimeFormatInfo properties for which the standard format strings are aliases, and does not list properties that may be accessed by custom format strings assigned to those aliased properties. In addition, the table lists only custom format specifiers that correspond to System.Globalization.DateTimeFormatInfo properties.

"d" (short date; standard format string)

DateTimeFormatInfo.ShortDatePattern, to define the overall format of the result string.

"D" (long date; standard format string)

DateTimeFormatInfo.LongDatePattern, to define the overall format of the result string.

"f" (full date / short time; standard format string)

DateTimeFormatInfo.LongDatePattern, to define the format of the date component of the result string.

DateTimeFormatInfo.ShortTimePattern, to define the format of the time component of the result string.

"F" (full date / long time; standard format string)

DateTimeFormatInfo.LongDatePattern, to define the format of the date component of the result string.

DateTimeFormatInfo.LongTimePattern, to define the format of the time component of the result string.

"g" (general date / short time; standard format string)

DateTimeFormatInfo.ShortDatePattern, to define the format of the date component of the result string.

DateTimeFormatInfo.ShortTimePattern, to define the format of the time component of the result string.

"G" (general date / long time; standard format string)

DateTimeFormatInfo.ShortDatePattern, to define the format of the date component of the result string.

DateTimeFormatInfo.LongTimePattern, to define the format of the time component of the result string.

"M", "m" (month/day; standard format string)

DateTimeFormatInfo.MonthDayPattern, to define the overall format of the result string.

"O", "o" (round-trip date/time; standard format string)

None.

"R", "r" (RFC1123; standard format string)

DateTimeFormatInfo.RFC1123Pattern, to define a result string that conforms to the RFC 1123 standard. The property is read-only.

"s" (sortable date/time; standard format string)

DateTimeFormatInfo.SortableDateTimePattern, to define a result string that conforms to the ISO 8601 standard. The property is read-only.

"t" (short time; standard format string)

DateTimeFormatInfo.ShortTimePattern, to define the overall format of the result string.

"T" (long time; standard format string)

DateTimeFormatInfo.LongTimePattern, to define the overall format of the result string.

"u" (universal sortable date/time; standard format string)

DateTimeFormatInfo.UniversalSortableDateTimePattern, to define a result string that conforms to the ISO 8601 standard for coordinated universal time. The property is read-only.

"U" (universal full date/time; standard format string)

DateTimeFormatInfo.FullDateTimePattern, to define the overall format of the result string.

"Y", "y" (year month; standard format string)

DateTimeFormatInfo.YearMonthPattern, to define the overall format of the result string.

"ddd" (custom format specifier)

DateTimeFormatInfo.AbbreviatedDayNames, to include the abbreviated name of the day of the week in the result string.

"g", "gg" (custom format specifier)

Calls the DateTimeFormatInfo.GetEraName(int) method to insert the era name in the result string.

"MMM" (custom format specifier)

DateTimeFormatInfo.AbbreviatedMonthNames, to include the abbreviated month name in the result string.

"MMMM" (custom format specifier)

DateTimeFormatInfo.MonthNames or DateTimeFormatInfo.MonthGenitiveNames, to include the full month name in the result string.

"t" (custom format specifier)

DateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator, to include the first character of the AM/PM designator in the result string.

"tt" (custom format specifier)

DateTimeFormatInfo.AMDesignator or DateTimeFormatInfo.PMDesignator, to include the full AM/PM designator in the result string.

":" (custom format specifier)

DateTimeFormatInfo.TimeSeparator, to include the time separator in the result string.

"/" (custom format specifier)

DateTimeFormatInfo.DateSeparator, to include the date separator in the result string.

Modifying DateTimeFormatInfo properties

You can change the result string produced by date and time format strings by modifying the associated properties of a writable System.Globalization.DateTimeFormatInfo object. To determine if a System.Globalization.DateTimeFormatInfo object is writable, use the DateTimeFormatInfo.IsReadOnly property. To customize a System.Globalization.DateTimeFormatInfo object in this way:

[The 'ordered' type of list has not been implemented in the ECMA stylesheet.]

There are two other ways to change the fomat of a result string:

Changing the short date pattern

The following example changes the format of a result string produced by the "d" (short date) standard format string. It changes the associated DateTimeFormatInfo.ShortDatePattern property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the DateTimeFormatInfo.ShortDatePattern property is changed.

code reference: System.Globalization.DateTimeFormatInfo.Class#10

Changing the date separator character

The following example changes the date separator character in a System.Globalization.DateTimeFormatInfo object that represents the formatting conventions of the fr-FR culture. The example uses the "g" standard format string to display the date both before and after the DateTimeFormatInfo.DateSeparator property is changed.

code reference: System.Globalization.DateTimeFormatInfo.Class#12

Changing day name abbreviations and the long date pattern

In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. It does this by assigning shorter day name abbreviations to the DateTimeFormatInfo.AbbreviatedDayNames array, and by modifying the custom format string assigned to the DateTimeFormatInfo.LongDatePattern property. This affects the result strings returned by the "D" and "f" standard format strings.

code reference: System.Globalization.DateTimeFormatInfo.Class#13

Ordinarily, the change to the DateTimeFormatInfo.LongDatePattern property also affects the DateTimeFormatInfo.FullDateTimePattern property, which in turn defines the result string returned by the "F" standard format string. To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the DateTimeFormatInfo.FullDateTimePattern property after the DateTimeFormatInfo.LongDatePattern property is modified.

Changing from a 12-hour clock to a 24-hour clock

For many cultures in the .NET Framework, the time is expressed by using a 12-hour clock and an AM/PM designator. The following example defines a ReplaceWith24HourClock method that replaces any time format that uses a 12-hour clock with a format that uses a 24-hour clock.

code reference: System.Globalization.DateTimeFormatInfo.Class#14

The example uses a regular expression to modify the format string. The regular expression pattern @"^(?<openAMPM>\s*t+\s*)? (?(openAMPM) h+(?<nonHours>[^ht]+)$ | \s*h+(?<nonHours>[^ht]+)\s*t+) is defined as follows:

^

Begin the match at the beginning of the string.

(?<openAMPM>\s*t+\s*)?

Match zero or one occurrence of zero or more white-space characters, followed by the letter "t" one or more times, followed by zero or more white-space characters. This capturing group is named openAMPM.

(?(openAMPM) h+(?<nonHours>[^ht]+)$

If the openAMPM group has a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t". The match ends at the end of the string. All characters captured after "h" are included in a capturing group named nonHours.

| \s*h+(?<nonHours>[^ht]+)\s*t+)

If the openAMPM group does not have a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t", followed by zero or more white-space characters. Finally, match one or more occurrences of the letter "t". All characters captured after "h" and before the white-spaces and "t" are included in a capturing group named nonHours.

The nonHours capturing group contains the minute and possibly the second component of a custom date and time format string, along with any time separator symbols. The replacement pattern HH${nonHours} prepends the substring "HH" to these elements.

Displaying and changing the era in a date

The following example adds the "g" custom format specifier to the DateTimeFormatInfo.LongDatePattern property of an object that represents the formatting conventions of the en-US culture. This addition affects the following three standard format strings:

The example also shows how to change the era name for a culture whose calendar has a single era. In this case, the en-US culture uses the Gregorian calendar, which is represented by a System.Globalization.GregorianCalendar object. The System.Globalization.GregorianCalendar class supports a single era, which it names A.D. (Anno Domini). The example changes the era name to C.E. (Common Era) by replacing the "g" custom format specifier in the format string assigned to the DateTimeFormatInfo.FullDateTimePatternproperty with a literal string. The use of a literal string is necessary, because the era name is typically returned by the DateTimeFormatInfo.GetEraName(int) method from private data in the culture tables supplied by either the .NET Framework or the Windows operating system.

code reference: System.Globalization.DateTimeFormatInfo.Class#11

Parsing date and time strings

Parsing involves converting the string representation of a date and time to a DateTime or DateTimeOffset value. Both of these types include the Parse, TryParse, ParseExact, and TryParseExact methods to support parsing operations. The Parse and TryParse methods convert a string that can have a variety of formats, whereas ParseExact and TryParseExact require that the string have a defined format or formats. If the parsing operation fails, Parse and ParseExact throw an exception, whereas TryParse and TryParseExact return false.

The parsing methods implicitly or explicitly use a System.Globalization.DateTimeStyles enumeration value to determine which style elements (such as leading, trailing, or inner white space) can be present in the string to be parsed, and how to interpret the parsed string or any missing elements. If you don't provide a System.Globalization.DateTimeStyles value when you call the Parse or TryParse method, the default is DateTimeStyles.AllowWhiteSpaces, which is a composite style that includes the DateTimeStyles.AllowLeadingWhite, DateTimeStyles.AllowTrailingWhite, and DateTimeStyles.AllowInnerWhite flags. For the ParseExact and TryParseExact methods, the default is DateTimeStyles.None; the input string must correspond precisely to a particular custom date and time format string.

The parsing methods also implicitly or explicitly use a System.Globalization.DateTimeFormatInfo object that defines the specific symbols and patterns that can occur in the string to be parsed. If you don't provide a System.Globalization.DateTimeFormatInfo object, the System.Globalization.DateTimeFormatInfo object for the current thread culture is used by default. For more information about parsing date and time strings, see the individual parsing methods, such as DateTime.Parse(string), DateTime.TryParse(string, DateTime@), DateTimeOffset.ParseExact(string, string, IFormatProvider), and DateTimeOffset.TryParseExact(string, string, IFormatProvider, DateTimeStyles, DateTimeOffset@).

The following example illustrates the culture-sensitive nature of parsing date and time strings. It tries to parse two date strings by using the conventions of the en-US, en-GB, fr-FR, and fi-FI cultures. The date that is interpreted as 8/18/2014 in the en-US culture throws a FormatException exception in the other three cultures because 18 is interpreted as the month number. 1/2/2015 is parsed as the second day of the first month in the en-US culture, but as the first day of the second month in the remaining cultures.

code reference: System.Globalization.DateTimeFormatInfo.Class#15

Date and time strings are typically parsed for two reasons:

The following sections discuss these two operations in greater detail.

Parsing user strings

When you parse date and time strings input by the user, you should always instantiate a System.Globalization.DateTimeFormatInfo object that reflects the user's cultural settings, including any customizations the user may have made. Otherwise, the date and time object may have incorrect values. For information about how to instantiate a System.Globalization.DateTimeFormatInfo object that reflects user cultural customizations, see the DateTimeFormatInfo and dynamic data section.

The following example illustrates the difference between a parsing operation that reflects user cultural settings and one that does not. In this case, the default system culture is en-US, but the user has used Control Panel, Region and Language to change the short date pattern from its default of "M/d/yyyy" to "yy/MM/dd". When the user enters a string that reflects user settings, and the string is parsed by a System.Globalization.DateTimeFormatInfo object that also reflects user settings (overrides), the parsing operation returns a correct result. However, when the string is parsed by a System.Globalization.DateTimeFormatInfo object that reflects standard en-US cultural settings, the parsing method throws a FormatException exception because it interprets 14 as the number of the month, not the last two digits of the year.

code reference: System.Globalization.DateTimeFormatInfo.Class#16

Serializing and deserializing date and time data

Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the DateTimeFormatInfo.InvariantInfo property, to generate and parse the data. The formatting and parsing operations should never reflect the conventions of the default culture. If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system.

If the time component of a date and time value is significant, it should also be converted to UTC and serialized by using the "o" or "r" standard format string. The time data can then be restored by calling a parsing method and passing it the appropriate format string along with the invariant culture as the provider argument.

The following example illustrates the process of round-tripping a date and time value. It serializes a date and time on a system that observes U.S. Pacific time and whose current culture is en-US.

code reference: System.Globalization.DateTimeFormatInfo.Class#17

It deserializes the data on a system in the Brussels, Copenhagen, Madrid and Paris time zone and whose current culture is fr-FR. The restored date is nine hours later than the original date, which reflects the time zone adjustment from eight hours behind UTC to one hour ahead of UTC. Both the original date and the restored date represent the same moment in time.

code reference: System.Globalization.DateTimeFormatInfo.Class#18

Thread Safety

This type is safe for multithreaded operations.

Requirements

Namespace: System.Globalization
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0