HOWTO · Csharp

在 C# 中將字串轉換為日期時間

在本指南中,我們將學習如何在 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,並在字串中定義了相同的格式。如果寫入的字串格式不正確,此函式將丟擲格式不正確的異常。