Home >Backend Development >C++ >How to Convert a 'yyyyMMddHHmmss' String to a C# DateTime Object?

How to Convert a 'yyyyMMddHHmmss' String to a C# DateTime Object?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 04:01:11548browse

How to Convert a

Converting a String Representation of a Date to a C# DateTime Object

When dealing with date and time data, it is often necessary to convert between string representations and DateTime objects. One common scenario is converting a string formatted using the "yyyyMMddHHmmss" pattern to a DateTime object.

To address this requirement, C# provides the DateTime.ParseExact method. By using this method, you can specify the exact format of the string and convert it to a DateTime object like this:

string dateString = "20090530123001";
DateTime dateTime = DateTime.ParseExact(dateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

The DateTime.ParseExact method requires the string to match the specified format precisely. If the string is not in the correct format, a FormatException will be thrown.

Alternatively, you can use the DateTime.TryParseExact method to handle cases where the string may not be in the correct format. This method returns a Boolean indicating whether the conversion was successful. You can use it as follows:

DateTime dateTime;
DateTime.TryParseExact(dateString, "yyyyMMddHHmmss",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);

By using the DateTime.ParseExact or DateTime.TryParseExact method, you can easily convert a string representation of a date to a DateTime object, allowing you to work with date and time data effectively in your C# applications.

The above is the detailed content of How to Convert a 'yyyyMMddHHmmss' String to a C# DateTime Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn