본문 바로가기
C#

C# DateTime.Parse

by violetoz 2013. 6. 1.

DateTime.Parse supports many formats. It is versatile. It can provoke a FormatException. We see examples of parsing formatted date and time strings, with examples from databases and Internet sources.

DateTime

Example

First we see that DateTime.Parse is a static method that you can call without using a DateTime instance. It returns a new DateTime instance, which is represented as a struct. If you provide no time, the time used is 12 AM.

Program that uses DateTime.Parse: C#

using System;

class Program
{
    static void Main()
    {
	string date = "2000-02-02";
	DateTime time = DateTime.Parse(date);
	Console.WriteLine(time);
    }
}

Output

2/2/2000 12:00:00 AM

TryParse

Programming tip

Whenever you have a string containing a date and time that may be invalid in formatting or that never occurred, you can use the DateTime.TryParse static method. It is in the System namespace.

Tip:It converts the string to a DateTime instance without raising an exception on errors.

TryParse

Formats

Here we see how the DateTime.Parse method works on various date time formats. Several time string formats were found on the Internet, and the DateTime.Parse method was used on each. Each call succeeded and returned the expected value.

Program that parses times: C#

using System;

class Program
{
    static void Main()
    {
	// Taken from my head
	string simpleTime = "1/1/2000";
	DateTime time = DateTime.Parse(simpleTime);
	Console.WriteLine(time);

	// Taken from HTTP header
	string httpTime = "Fri, 27 Feb 2009 03:11:21 GMT";
	time = DateTime.Parse(httpTime);
	Console.WriteLine(time);

	// Taken from w3.org
	string w3Time = "2009/02/26 18:37:58";
	time = DateTime.Parse(w3Time);
	Console.WriteLine(time);

	// Taken from nytimes.com
	string nyTime = "Thursday, February 26, 2009";
	time = DateTime.Parse(nyTime);
	Console.WriteLine(time);

	// Taken from this site
	string perlTime = "February 26, 2009";
	time = DateTime.Parse(perlTime);
	Console.WriteLine(time);

	// Taken from ISO Standard 8601 for Dates
	string isoTime = "2002-02-10";
	time = DateTime.Parse(isoTime);
	Console.WriteLine(time);

	// Taken from Windows file system Created/Modified
	string windowsTime = "2/21/2009 10:35 PM";
	time = DateTime.Parse(windowsTime);
	Console.WriteLine(time);

	// Taken from Windows Date and Time panel
	string windowsPanelTime = "8:04:00 PM";
	time = DateTime.Parse(windowsPanelTime);
	Console.WriteLine(time);
    }
}

Output

1/1/2000 12:00:00 AM
2/26/2009 7:11:21 PM
2/26/2009 6:37:58 PM
2/26/2009 12:00:00 AM
2/26/2009 12:00:00 AM
2/10/2002 12:00:00 AM
2/21/2009 10:35:00 PM
2/26/2009 8:04:00 PM

SQL dates

SQL: Structured Query Language

The DateTime.Parse method can also be used on SQL Server and MySQL date strings. It is best to use an ADO.NET provider for this. But often when you are working with the data in text format it is ideal to use DateTime.Parse.

SQL

ParseExact

Program icon

In some scenarios you can use DateTime.ParseExact if you have a confusing or non-standard date time string. This is ideal when your date string could be interpreted wrong by .NET, but it is valid.

Tip:Use the formatting characters to specify how ParseExact and TryParseExact work.

You must specify the exact formatting string for DateTime.ParseExact. You need to use a format string that has letters in it that tell ParseExact where to read in the values from your string.

Program that uses DateTime.ParseExact: C#

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
	string dateString = "Mon 16 Jun 8:30 AM 2008"; // Modified from MSDN
	string format = "ddd dd MMM h:mm tt yyyy";

	DateTime dateTime = DateTime.ParseExact(dateString, format,
	    CultureInfo.InvariantCulture);
	Console.WriteLine(dateTime);
    }
}

Output

6/16/2008 8:30:00 AM

The strings indicate where the values are located in the string. The date string here is unusual. But it is parsed correctly. DateTime.ParseExact will not let you create a date that it deems to not exist in the world.

So:If you change Mon to Tue in the above example, it won't work, because Jun 16 was a Monday.

FormatException

Warning: exclamation mark

We see an exception raised by DateTime.ParseExact when you specify a date that never actually existed or will exist in the world. If Tuesday was the tenth of a month, you cannot make a DateTime where it is the eleventh.

Warning:DateTime.ParseExact throws an exception, a FormatException instance, in this case.

FormatException
Program that throws exception in ParseException: C#

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
	string dateString = "Tue 16 Jun 8:30 AM 2008"; // <-- Never existed!
	string format = "ddd dd MMM h:mm tt yyyy";
	DateTime dateTime = DateTime.ParseExact(dateString,
	    format, CultureInfo.InvariantCulture);
    }
}

Output

Unhandled Exception: System.FormatException:
    String was not recognized as a valid DateTime
    because the day of week was incorrect.

In this example, the day of the week was found to be incorrect. When the date format is invalid, an exception will also be thrown. DateTime.ParseExact is useful in cases where you have confusing dates that DateTime.Parse doesn't handle.

But:My experience is that you want to use DateTime.Parse or TryParse in most cases.

Format strings

Format

The DateTime format strings supported in .NET are described in another article at this site. The article has summaries and notes on many of the formatting strings, as well as lists of what they can output.

DateTime Format

Summary

Summary

We used the DateTime.Parse method. We saw what strings it works on. The tester-doer pattern used in TryParse is probably the most effective in many real-world programs, but the Parse method itself is also useful in some situations.