Home >Backend Development >C++ >How Can I Parse a String into a DateTime Object in C#?

How Can I Parse a String into a DateTime Object in C#?

DDD
DDDOriginal
2025-02-02 03:11:08326browse

How Can I Parse a String into a DateTime Object in C#?

Analyze the string as the Datetime object

In the programming world, processing date and time are a common task. Sometimes, we will encounter these values ​​storage as string, for example:

2009-05-08 14: 40: 52,531

In order to convert these strings into available DateTime objects, we have several options. One method is to specify the custom format string, as shown below:

By specifying the custom format string, we can ensure that the elements of the string (year-month-day, hour-second-seconds, and milliseconds) are aligned with the expected DateTime format. This method provides a reliable and efficient way to convert the string to Datetime object.
<code class="language-csharp">using System;
using System.Globalization;

namespace DateTimeParsingExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 指定自定义格式字符串以适应字符串的组成
            string formatString = "yyyy-MM-dd HH:mm:ss,fff";

            // 使用自定义格式解析字符串
            DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", formatString, CultureInfo.InvariantCulture);

            // 输出解析的日期
            Console.WriteLine(myDate.ToString()); // 显示 2009-05-08 14:40:52,531
        }
    }
}</code>

The above is the detailed content of How Can I Parse a String into a DateTime Object in C#?. 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