在 C# 中獲取當前時間

Muhammad Maisam Abbas 2024年2月16日
在 C# 中獲取當前時間

本教程將討論在 C# 中使用字串變數獲取當前時間的方法。

使用 C# 中的 DateTime.Now 屬性獲取當前時間

DateTime 結構表示 C# 中的時間例項。DateTime 結構的 DateTime.Now 屬性獲取以本地時間表示的本地計算機的當前日期和時間。我們可以使用 C# 中的 DateTime.ToString() 方法DateTime.Now 屬性的結果轉換為字串變數。下面的程式碼示例向我們展示瞭如何使用 C# 中的 DateTime.Now 屬性在字串變數中獲取本地計算機的當前時間。

using System;

namespace get_current_time {
  class Program {
    static void Main(string[] args) {
      string datetime = DateTime.Now.ToString("hh:mm:ss tt");
      Console.WriteLine(datetime);
    }
  }
}

輸出:

02:57:57 PM

我們用 DateTime.Now 屬性和 C# 中的 DateTime.ToString() 函式將我們本地機器的當前時間以 hh:mm:ss tt 格式儲存在 datetime 字串變數中。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Csharp DateTime