web analytics
Converting String to DateTime in C# Options
codeling
Posted: Tuesday, June 20, 2017 11:05:46 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 836
Points: 3498

The following code demonstrates how to use the ParseExact method to convert a string to DateTime value.

 
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string dateString, format;  
      DateTime result;
      CultureInfo provider = CultureInfo.InvariantCulture;

      // Parse date-only value with invariant culture.
      dateString = "06/15/2008";
      format = "d";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      } 

      // Parse date-only value without leading zero in month using "d" format.
      // Should throw a FormatException because standard short date pattern of 
      // invariant culture requires two-digit month.
      dateString = "6/15/2008";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse date and time with custom specifier.
      dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
      format = "ddd dd MMM yyyy h:mm tt zzz";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

      // Parse date and time with offset but without offset's minutes.
      // Should throw a FormatException because "zzz" specifier requires leading  
      // zero in hours.
      dateString = "Sun 15 Jun 2008 8:30 AM -06";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }   
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      } 

      dateString = "15/06/2008 08:30";
      format = "g";
      provider = new CultureInfo("fr-FR");
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }   
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      } 

      // Parse a date that includes seconds and milliseconds
      // by using the French (France) and invariant cultures.
      dateString = "18/08/2015 06:30:15.006542";
      format = "dd/MM/yyyy HH:mm:ss.ffffff";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }
   }
}
// The example displays the following output:
//       06/15/2008 converts to 6/15/2008 12:00:00 AM.
//       6/15/2008 is not in the correct format.
//       Sun 15 Jun 2008 8:30 AM -06:00 converts to 6/15/2008 7:30:00 AM.
//       Sun 15 Jun 2008 8:30 AM -06 is not in the correct format.
//       15/06/2008 08:30 converts to 6/15/2008 8:30:00 AM.
//       18/08/2015 06:30:15.006542 converts to 8/18/2015 6:30:15 AM.
Sponsor
Posted: Tuesday, June 20, 2017 11:05:46 AM
 
codeling
Posted: Thursday, September 14, 2017 11:45:21 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 836
Points: 3498

Parse(), TryParse() and ParseExact() Methods

The DateTime struct has a lot of methods for parsing a string into a DateTime.  Most everyone has used the Parse() method, but the cost of the exception throws on an error can become a performance bottleneck if improperly formatted input is possible. 

 string logString = "20111231 031505";
 DateTime logEntryTime;
 
 try
 {
     logEntryTime = DateTime.Parse(logString);
 }
 catch (Exception ex)
 {
     // the above will throw
     Console.WriteLine("Didn't understand that DateTime.");
 }

The TryParse() methods have much the same signature as Parse(), except that they take a final out parameter of DateTime where the value is placed (if successful), and return a bool that indicates if the parse was successful or not. Use TryParse() when you want to be able to attempt a parse and handle invalid data immediately (instead of bubbling up the exception). Thus, the code above could be rewritten as:

 string input = "02/30/2010 12:35";
 DateTime recordDate;
 
 // let's say we want to parse the date, but if we can't, then we'll assume now...
 if(!DateTime.TryParse(input, out recordDate))
 {
     recordDate = DateTime.Now;
 }

What if you were reading data from a file, and the DateTime contained in it was a non-standard format.  For example, let’s say we’re parsing a log file that begins with a timestamp that is a date in the format yyyyMMdd HHmmss (like 20111231 031505 for 12/31/2011 03:15:05 AM), in this situation you should use ParseExact() when the format you are expecting is not a standard format, or when you want to limit to one particular standard format for efficiency.

 string logString = "20111231 031505";
 DateTime logEntryTime;
 logEntryTime = DateTime.ParseExact(logString, "yyyyMMdd HHmmss", null);

Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.