Convert String to DateTime in C#
In C#, there are multiple ways to convert a string representation of a date and time into a DateTime object. One common scenario involves converting a string formatted as "yyyyMMddHHmmss" into a DateTime object. This format is often encountered when dealing with dates and times stored in databases or other text-based formats.
Using DateTime.ToString()
To convert a string in the "yyyyMMddHHmmss" format to a DateTime object, you can use the DateTime.ToString() method. Here's an example:
string strDate = "20090530123001"; DateTime dateTime = DateTime.ParseExact(strDate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
In this code, the ParseExact method takes the string to be converted, the desired format string, and the culture information for handling date and time conversions. The InvariantCulture is used to ensure that the conversion is culture-independent.
Using Convert.ToDateTime()
Alternatively, you can use the Convert.ToDateTime() method to convert a string to a DateTime object. However, this method requires the string to be in a specific format. For example:
string strDate = "2009-05-30 12:30:01"; DateTime dateTime = Convert.ToDateTime(strDate);
In this case, the string is in the "yyyy-MM-dd HH:mm:ss" format, which is supported by the Convert.ToDateTime() method.
Handling Format Exceptions
If the input string is not in the expected format, both DateTime.ParseExact() and Convert.ToDateTime() will throw a FormatException. If you want to catch these exceptions gracefully, you can use the TryParseExact() or TryParse methods, respectively. For example:
DateTime dateTime; if (DateTime.TryParseExact(strDate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { // Conversion successful } else { // Conversion failed }
Conclusion
Converting a string to a DateTime object is a common operation in C#. By using the appropriate conversion method and handling format exceptions correctly, you can ensure that your date handling is accurate and robust.
The above is the detailed content of How to Convert a String to a DateTime Object in C#?. For more information, please follow other related articles on the PHP Chinese website!