There are many different ways to represent dates and times as text. For example, 1st June 2003, 1/6/2003, 6/1/2003, and 1-Jun-2003 are all possible representations of the same date, and 16:43 and 4:43pm can both be used to represent the same time. The static DateTime.Parse method provides a flexible mechanism by which to create DateTime instances from a wide variety of string representations.
The Parse method goes to great lengths to generate a DateTime from a given string. It will even attempt to generate a DateTime from a string containing partial or erroneous information and will substitute defaults for those values it finds missing. Missing date elements default to the current date, and missing time elements default to 12:00:00 am. After all efforts, if Parse can't create a DateTime, it throws a System.FormatException. The following code demonstrates the flexibility of the Parse method.
// 01/09/2001 00:00:00 DateTime dt1 = DateTime.Parse("Sep 2001"); // 05/09/2001 14:15:33 DateTime dt2 = DateTime.Parse("Wed 5 September 2001 14:15:33"); // 05/09/2001 00:00:00 DateTime dt3 = DateTime.Parse("5,9,01"); // 05/09/2001 14:15:33 DateTime dt4 = DateTime.Parse("5/9/2001 14:15:33"); // 01/07/2003 14:15:00 DateTime dt5 = DateTime.Parse("2:15 PM");
The Parse method is both flexible and forgiving. However, for many applications this level of flexibility is unnecessary. Often you will want to ensure that DateTime parses only strings that match a specific format. In these circumstances, use the ParseExact method instead of Parse. The simplest overload of the ParseExact method takes three arguments: the time and date string to parse, a format string that specifies the structure that the time and date string must have, and an IFormatProvider reference that provides culture specific information to the ParseExact method. If the IFormatProvider is null, the current thread's culture information is used.
The time and date must meet the requirements specified in the format string or ParseExact will throw a System.FormatException. You use the same format specifiers for the format string as you use to format a DateTime for display as a string. This means you can use both standard and custom format specifiers. The following code demonstrates the use of the ParseExact method. Refer to the documentation for the System.Globalization.DateTimeFormatInfo class in the .NET Framework SDK document for complete details on all available format specifiers.
// Parse only strings containing LongTimePattern DateTime dt6 = DateTime.ParseExact("2:13:30 PM", "h:mm:ss tt", null); // Parse only strings containing RFC1123Pattern DateTime dt7 = DateTime.ParseExact( "Wed, 05 Sep 2001 14:13:30 GMT", "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", null); // Parse only strings containing MonthDayPattern DateTime dt8 = DateTime.ParseExact("September 03", "MMMM dd", null);
No comments:
Post a Comment