User Tools

Site Tools


prog:csharp:250326-01:index

C#: 如何取得並格式化系統時間 (2025-03-26)

Local Backup

  • 在這篇教學中,我們將學習如何在C#程式中取得系統時間並進行格式化,以滿足不同需求的日期和時間顯示。

取得系統時間

  • 在C#中,我們可以使用 DateTime.Now 屬性來取得當前的系統時間。
  • 取得並顯示系統時間:
    using System;
    
    class Program
    {
        static void Main()
        {
            // 取得當前的系統時間
            DateTime currentTime = DateTime.Now;
    
            // 顯示結果
            Console.WriteLine("現在的系統時間是:" + currentTime);
        }
    }
  • 執行程式,您將看到類似於 2023/08/03 14:30:20 的輸出,這取決於您的當地文化設定。

格式化日期和時間

  • 預設情況下,系統時間是以當地文化設定的預設格式呈現的。但有時候我們需要以特定格式顯示日期和時間。在C#中,我們可以使用 DateTime 的 ToString 方法來實現格式化。
  • 以下是一些常見的日期和時間格式範例:
  • 格式化日期和時間
    using System;
    
    class Program
    {
        static void Main()
        {
            DateTime currentTime = DateTime.Now;
    
            // 顯示日期和時間,格式為 yyyy/MM/dd HH:mm:ss
            string formattedDateTime = currentTime.ToString("yyyy/MM/dd HH:mm:ss");
            Console.WriteLine("格式化的日期時間:" + formattedDateTime);
        }
    }

格式化日期

  • using System;
    
    class Program
    {
        static void Main()
        {
            DateTime currentTime = DateTime.Now;
    
            // 顯示日期,格式為 yyyy/MM/dd
            string formattedDate = currentTime.ToString("yyyy/MM/dd");
            Console.WriteLine("格式化的日期:" + formattedDate);
        }
    }

格式化時間

  • csharpCopy code
    using System;
    
    class Program
    {
        static void Main()
        {
            DateTime currentTime = DateTime.Now;
    
            // 顯示時間,格式為 HH:mm:ss
            string formattedTime = currentTime.ToString("HH:mm:ss");
            Console.WriteLine("格式化的時間:" + formattedTime);
        }
    }
  • 請注意,在格式字串中,yyyy 表示四位數的年份,MM 表示兩位數的月份,dd 表示兩位數的日期,HH 表示24小時制的兩位數小時,mm 表示兩位數的分鐘,ss 表示兩位數的秒數。
  • 使用這些格式範例,您可以根據需要來自訂日期和時間的顯示格式。這些技巧對於日誌記錄、報告產生和使用者介面的日期/時間顯示都很有用。
  • 這就是在C#中取得系統時間並進行格式化的基本步驟。
  • 38 person(s) visited this page until now.

prog/csharp/250326-01/index.txt · Last modified: 2025/03/26 10:12 (external edit)