Home >Backend Development >C++ >How to Convert 'yyyy-MM-dd HH:mm:ss,fff' String to DateTime Object?

How to Convert 'yyyy-MM-dd HH:mm:ss,fff' String to DateTime Object?

Barbara Streisand
Barbara StreisandOriginal
2025-02-02 03:21:10402browse

How to Convert

String to DateTime Conversion: A Detailed Guide

Frequently, developers need to convert strings into DateTime objects. Let's examine a specific example: transforming a string like "2009-05-08 14:40:52,531" into a usable DateTime object.

This task demands accuracy, particularly due to the 24-hour time format and the comma separating the milliseconds. The solution lies in employing a precise custom format string.

Here's how to achieve this conversion:

<code class="language-csharp">DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);</code>

Let's break down this code:

  • DateTime.ParseExact() is the core function for this conversion. It parses a string according to a specified format.
  • "yyyy-MM-dd HH:mm:ss,fff" is the crucial custom format string. It precisely mirrors the input string's structure.
  • System.Globalization.CultureInfo.InvariantCulture ensures consistent results, independent of regional settings on the system.

This method guarantees accurate conversion of a date and time string into a DateTime object, enabling further date and time manipulation within your application.

The above is the detailed content of How to Convert 'yyyy-MM-dd HH:mm:ss,fff' String to 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