TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# DateTime.Parse: Convert String to DateTime

Handle strings containing dates with DateTime.Parse. Convert a string to a DateTime.
DateTime.Parse. An ancient civilization writes dates in unknown ways. DateTime.Parse() handles modern formats. When we know the format is correct, use Parse—otherwise, prefer TryParse.DateTime
Notes, forms. We can parse formatted date and time strings. Formats from various databases and Internet sources can be handled. Parse, and ParseExact, are shown.
An example. DateTime.Parse is a static method. It returns a new DateTime instance, which is represented as a struct. If you provide no time, the time "12 AM" is used.Static
C# program that uses DateTime.Parse 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
Formats. DateTime.Parse works on various date time formats. Several time string formats were found on the Internet, and the DateTime.Parse method was used on them.
C# program that parses times using System; class Program { static void Main() { // A simple example. 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
ParseExact. You can use DateTime.ParseExact if you have a confusing or non-standard 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.

Note: You need to use a format string that has letters in it that tell ParseExact where to read in the values from your string.

Invalid: DateTime.ParseExact will not let you create a date that it deems to not exist in the world.

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

C# program that uses DateTime.ParseExact using System; using System.Globalization; class Program { static void Main() { string dateString = "Mon 16 Jun 8:30 AM 2008"; 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
FormatException. We see an exception when you specify a date that cannot exist. 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

Result: The day of the week was found to be incorrect. DateTime.ParseExact can help with dates that DateTime.Parse doesn't handle.

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

C# program that throws exception in ParseException 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.
Dates from SQL. SQL date strings can be handed with DateTime.Parse. This is useful when you have database text-only data. DateTime.Parse works on the date time format in the MySQL database.

Note: Consider the statements here. Each DateTime.Parse call here succeeds, and returns the correct value.

Important: Normally, MySQL dates and times are stored in columns of types DATETIME, DATE, and TIMESTAMP.

C# program that parses MySQL dates using System; class Program { static void Main() { // Taken from MySQL: SELECT CURTIME() // SELECT TIME(...) string mySqlTime = "23:50:26"; DateTime time = DateTime.Parse(mySqlTime); // Taken from MySQL: SELECT TIMESTAMP(...) string mySqlTimestamp = "2003-12-31 00:00:00"; time = DateTime.Parse(mySqlTimestamp); Console.WriteLine(time); // Taken from MySQL: SELECT CURDATE() // SELECT DATE(...) string mySqlDate = "2008-06-13"; time = DateTime.Parse(mySqlDate); Console.WriteLine(time); } } Output 12/31/2003 12:00:00 AM 6/13/2008 12:00:00 AM
SQL, example 2. With the examples from Microsoft SQL Server, the DateTime.Parse method will parse the string representations from the database.

Tip: When using the valid date formats from MySQL and SQL Server, you can use DateTime.Parse to get the dates from the SQL strings.

C# program that uses DateTime.Parse with SQL Server using System; class Program { static void Main() { // Taken from SQL SERVER: SELECT GETDATE() // SELECT GETUTCDATE() string sqlServerDate = "2007-04-30 13:10:02.047"; DateTime time = DateTime.Parse(sqlServerDate); Console.WriteLine(time); // Taken from SQL SERVER: SELECT SYSDATETIME() // SELECT SYSUTCDATETIME() string sqlSysDate = "2007-04-30 20:10:02.0474381"; time = DateTime.Parse(sqlSysDate); Console.WriteLine(time); // Taken from SQL SERVER: SELECT SYSDATETIMEOFFSET() string sqlSysDateOffset = "2007-04-30 13:10:02.0474381 -07:00"; time = DateTime.Parse(sqlSysDateOffset); Console.WriteLine(time); } } Output 4/30/2007 1:10:02 PM 4/30/2007 8:10:02 PM 4/30/2007 1:10:02 PM
TryParse. Whenever you have a string containing a date and time that may be invalid in formatting or that never occurred, you can use DateTime.TryParse.

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

DateTime.TryParse
Format strings. The DateTime format strings supported in .NET are explored. The article has summaries and notes on many of the formatting strings, as well as lists of what they can output.DateTime Format
A 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf