在 C# 中将字符串转换为日期时间

本指南将教我们在 C# 中将字符串转换为日期时间。我们还可以将字符串转换为特定格式的日期时间,例如 yyyy-mm-dd hh mm ss

我们需要熟悉 CultureInfo 才能理解这一点。让我们深入了解本指南并了解有关它的所有内容。

C# 中将字符串转换为日期时间

要将字符串转换为日期时间,我们已经知道字符串应该以特定格式写入。一种清楚地显示日、月和年的格式。

只有这样,我们才能继续进行上述操作;此方法需要有关 CultureInfo 的知识。让我们先了解一下。

首先,你需要导入 using System.Globalization; 图书馆使用文化信息及其功能。

语法如下:CultureInfoCultureInfo 包含文化、书写系统、文化名称、字符串的排序顺序以及日期和数字的实际格式的信息。

其中的对象由诸如 CompareInfo 之类的属性返回。文化被分组为三种不变的文化之一。

DateTimeFormatNumberFormat 也反映了格式约定和字符串比较。

在这里了解更多关于 CultureInfo

你需要在 DateTime.ParseExact() 中传递特定的书面字符串以及格式和文化信息。

以特定格式编写字符串后,你需要在将其传递到 DateTime.ParseExact() 时匹配相同的格式。现在,让我们了解将字符串转换为日期时间的代码和实现。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization; ///To use CultureInfo
namespace String_To_Date_Time
{
    class Program
    {
        static void Main(string[] args)
        {
            // First Method Using DateTime.ParseExact;
            string str = "2022-11-22 13:22";
            DateTime d =DateTime.ParseExact(str, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
            // Throws Exception if the Format Is Incorrect...
            Console.WriteLine(d);
            Console.Read();
        }
    }
}

我们在函数内部传递了字符串 str,并在字符串中定义了相同的格式。如果写入的字符串格式不正确,此函数将抛出格式不正确的异常。