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
Release: 2025-02-02 03:11:08
Original
296 people have browsed it

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.
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
        }
    }
}
Copy after login

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 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template