Date/Time formatting of strings

  • Article
  • Quick Read Time: 7 minutes

To create DateTime objects from strings, you must first specify the format of the dates and times in the string. Timekeeping systems in various civilizations have different sequences for days, months, and years. There are a few different ways that time can be represented; some use a 24-hour clock, while others distinguish between "am" and "pm." Date is all that's required for some applications. Some people just need some time. For others, the time and date must be included. Converting strings to DateTime objects allows you to specify the expected format and the specifics of a date and time that your program requires. Converting text into a DateTime involves three steps:

  1. Date and time representations in text must conform to a standard format, which must be specified.
  2. For a given date and time, you can choose the culture in which it will be displayed.
  3. In the case of the date and time, you have the option of customizing how any blanks in the textual representation are filled in.

Many different formats for representing dates and times can be converted using the Parse and TryParse methods. Date and time format strings can be used in conjunction with the ParseExact and TryParseExact methods to produce a string representation that is in the correct format. Check out the custom date and time format strings article and the regular date and time format strings article for more details.

A greater degree of discretion over how text is to be interpreted as a date and time is provided by the current DateTimeFormatInfo object. The properties of a DateTimeFormatInfo specify the separators between the date and time, the names of the months, the names of the days, and the format for the "AM" and "PM" notations. CultureInfo.CurrentCulture will return a CultureInfo object with a CultureInfo.DateTimeFormat property that describes the current culture. The IFormatProvider parameter of a parsing method is where you put in the details of the culture or preferences you're looking for. Use a CultureInfo object to represent a culture or a DateTimeFormatInfo object to specify a date and time format when setting the IFormatProvider.

Information about dates and times may be incomplete in the textual representation. It's safe to say that when you say "March 12," most people automatically think of the current year. Similarly, "March 2018" denotes March of the current calendar year. In most cases, the only elements of a textual representation of time are the hours, minutes, and AM/PM indicators. Parsing techniques deal with this data gap by making reasonable assumptions:

  • If only the time is given, the current date is substituted.
  • When only the date is given, midnight is assumed for the time component.
  • In the absence of a year in a given date, the current year will be assumed.
  • In the absence of a specific day of the month, the first of the month is assumed.

The month and either the day or year must be present if the string contains a date. If there is a time mentioned, it must contain the hour, minutes, and either the AM/PM indicator or the time zone designation.

To disable this behavior, set the NoCurrentDateDefault constant. This constant assigns the value 1 to the year, month, and day properties if they are undefined. This is the behavior shown by the last Parse example.

The string representation of a date and time can include not only a date component and a time component, but also an offset that indicates how far the time is from Coordinated Universal Time (UTC). A time seven hours ahead of UTC is defined by the string "2/14/2007 5:32:00 -7:00," for instance. A DateTime object with DateTimeKind.Unspecified as its Kind property is returned by parsing if an offset is absent from the string representation of a time. DateTime objects with the Kind property set to DateTimeKind.Local are returned from parsing if an offset is provided. Its value also takes into account your computer's time zone. Changing the DateTimeStyles value in conjunction with the parsing method can alter this behavior.

An ambiguous numerical date can also be interpreted with the help of the format provider. The date represented by the string "02/03/04" does not clearly indicate the month, day, or year. Similar date formats in the format provider's order are used to interpret the components.


In order to convert a string into a DateTime object, we can use the DateTime.Parse method, as shown in the following example. The culture of the ongoing discussion is utilized in this illustration. In the event that the CultureInfo associated with the current culture is unable to interpret the input string, a FormatException is thrown.


All the code snippets presented here are browser-based examples of C#. To view the results, hit the Run button. You can also make changes and try out different variations.


You can find C# and Visual Basic versions of these samples in the GitHub documentation repository.

dateInput = "January 1, 2009" in a string DateTime.parse(var parsedDate) Parse(dateInput); Console WriteLine(parsedDate); This code, when run on a machine set to the English (US) culture, displays: // 1/1/2009 00:00:00 Initialize Local Variable: MyString = "Jan 1, 2009" Replace MyDateTime With: DateTime = DateTime Parse(MyString) Console WriteLine(MyDateTime) Displays the following text when run in the English (US) culture: ' 1/1/2009 00:00:00

When parsing a string, you can also specify the culture whose norms will be applied. CultureInfo.DateTimeFormat property returns a collection of standard DateTimeFormatInfo objects, from which you must select one. Using a format provider, the following code converts a German string into a DateTime format. A CultureInfo object representing the de-DE culture is generated. This CultureInfo object guarantees correct string parsing. All options available in the CurrentCulture of the CurrentThread are ruled out by this procedure.

cultureInfo = new CultureInfo("de-DE"); As in: string dateString = "12 June 2008"; In other words: var dateTime = DateTime To convert a string of dates into a cultural context, use parse(dateString, cultureInfo). Console WriteLine(dateTime); This is the output shown in the example: // // 6/12/2008 00:00:00 CultureInfo("de-DE") = MyCultureInfo.Dim Create Variable "MyString" Of Type "String" = "12 Juni 2008" Convert MyDateTime ToDateTime AsDateTime = DateTime Function: parse(MyString, MyCultureInfo) Console WriteLine(MyDateTime) As a result of running the example, we get the following results: ' 6/12/2008 00:00:00

On the other hand, you can use Parse method overloads to define your own format providers. Non-standard formats cannot be parsed using the Parse method. The ParseExact method should be used if the date and time are expressed in a non-standard format.

Unspecified fields can use the The following example uses the DateTimeStyles enumeration to indicate that the current date and time should not be appended to the DateTime.

CultureInfo("de-DE") = new CultureInfo("cultureInfo"); When you use the string dateString = "12 Juni 2008,"; When working with DateTime variables, set var dateTime = DateTime. It uses a parse(dateString, cultureInfo, DateTimeStyles NoCurrentDateDefault); Console WriteLine(dateTime); If the current culture is American English, the example will display the following: // // 6/12/2008 00:00:00 Represent MyCultureInfo in the Dim Space with the New CultureInfo("de-DE"). To create a new string, use the following syntax: Dim MyString As String = "12 Juni 2008" MyDateTime.DateTime = DateTime.DateTime Applying the function Parse(MyString, MyCultureInfo, DateTimeStyles NoCurrentDateDefault) Console WriteLine(MyDateTime) If the current culture is set to "en-US," the example will display the following: ' 6/12/2008 00:00:00


Any string that matches one of the predefined patterns can be parsed into a DateTime object using the DateTime.ParseExact method. A FormatException is thrown when this method is called with a string that doesn't match one of the allowed formats. Dates and times can be formatted using either the built-in format specifiers or a combination of those. Custom format specifiers allow you to build a unique recognition string. Learn more about the parameters in standard date and time format strings and personalized date and time format strings.

Here's how to use the DateTime.ParseExact method: pass a string object, a format specifier, and a CultureInfo object to it. Only strings that use the long date pattern typical of the en-US culture can be parsed by this ParseExact method.

CultureInfo is set to a new instance of CultureInfo("en-US"); var cultureInfo. dateStrings[:] = "Friday, April 10, 2009", "Friday, April 10, 2009"; dateStrings.foreach("dateString," in dateStrings) { try { dateTime variable = DateTime; Specifically: ParseExact(dateString, "D", cultureInfo); Console WriteLine(dateTime); } The catch (FormatException) { Console Error parsing date "0": WriteLine(dateString), "Unable to parse '0'", } } The following is the output of the example code: Friday, April 10, 2009 // Parsing error // 4/10/2009 00:00:00 Change MyCultureInfo to NewCultureInfo("en-US"). Friday, April 10th, 2009" "Friday, April 10th, 2009" Dim MyString() As String = "Friday, April 10th, 2009" Replace (for each dateString in mystring) with: Try Set MyDateTime To DateTime = DateTime Use ParseExact(dateString, "D", MyCultureInfo) Console WriteLine(MyDateTime) FormatException: catch e as String Console Date string not recognized, WriteLine("Unable to parse '0'", dateString) End Try Next The following results are shown in the example: Error parsing date: "April 10, 2009" ' 4/10/2009 00:00:00

Both Parse and ParseExact have an additional parameter, IFormatProvider, that supplies culturally relevant formatting details for the string. The CultureInfo object representing a culture norm or the DateTimeFormatInfo object obtained via the CultureInfo.DateTimeFormat property make up the IFormatProvider object. An optional second string or array of strings is used by ParseExact to define one or more unique date and time formats.

See also

Convert Chinese Yuan to United States Dollar
Convert Chinese Yuan to United States Dollar

If you're thinking about taking a trip to the United States, you might consider exchanging some of your money into U.S. dollars, which is the official currency of the country. The international symbol for the currency is USD.USD is also the official currency in a few other countries, including Ecuador

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-08-07 00:02:33
Chinese Yuan to United States Dollar Conversion: CNY to USD
Chinese Yuan to United States Dollar Conversion: CNY to USD

If you're considering a journey to the United States, it might be beneficial to convert some of your money into U.S. dollars, which is the official currency of the country. The internationally recognized symbol for this currency is USD.Additionally, USD serves as the official currency in Ecuador and El

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-08-07 00:02:20
Convert Decimal to Inches with an Inch Fraction Calculator
Convert Decimal to Inches with an Inch Fraction Calculator

Utilize our inch-to-fraction calculator to effortlessly perform conversions between inch fractions, decimal values, metric measurements, and feet. Effective Techniques for Calculating Inch FractionsInches can be represented as fractions or decimals. When dealing with inch fractions, it is vital to

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-08-06 00:13:21
Kilowatt to British Thermal Unit (International)/hour Conversion
Kilowatt to British Thermal Unit (International)/hour Conversion

Please enter the necessary values below to convert kilowatts [kW] to British thermal units per hour [Btu/h], or the other way around.Description: A kilowatt (symbol: kW) is a unit of power within the International System of Units (SI). The watt, after the Scottish inventor James Watt, serves as the base

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-08-06 00:12:10
Showing page 1 of 13

VyConvert - since 2022
, US

Facebook| | DMCA

Gen in 0.2335 secs