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

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

Patricia Arquette
Release: 2024-12-30 06:46:10
Original
1024 people have browsed it

How to Convert a

Convert String to DateTime in C#

Converting a string date to a DateTime object in C# can be a challenging task, especially when dealing with non-standard formats. One such format is "yyyyMMddHHmmss", which represents a date without separators.

Problem:

Consider the following string date:

20090530123001
Copy after login

This string was created using dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture). How can we convert it back into a proper DateTime object?

Solution:

The simplest approach is to use the DateTime.ParseExact method. This method takes three parameters:

  • The string to be converted
  • The format of the string
  • The culture information (optional)

For the given string, we can use the following code:

DateTime dateTime = DateTime.ParseExact("20090530123001", "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
Copy after login

This will successfully convert the string into a DateTime object.

Handling Invalid Formats:

However, if the string may not always be in the correct format, using ParseExact can result in a FormatException. To avoid this, you can use the DateTime.TryParseExact method instead. This method takes the same parameters as ParseExact but returns a boolean value indicating whether the conversion was successful.

The following code demonstrates how to use TryParseExact:

DateTime dateTime;
if (DateTime.TryParseExact("20090530123001", "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
    // Conversion successful
}
else
{
    // Conversion failed
}
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template