IRONSOFTWAREHOME
開發者更新

C# 中的 DateTime 對象(對於開發者的運行原理)

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月23日

DateTime 物件在C#中是處理 .NET Framework 應用程式中日期和時間的基礎。 它們提供一組強大的功能來操作、格式化和比較日期和時間。

本文旨在提供 C# 中 DateTime 物件的綜合概覽,涵蓋其建立、操作、格式化和常見的使用案例。 在文章的末尾,我們還將探索如何使用 IronPDF 來自 Iron Software 在 C# 應用程式中動態生成 PDF 文件。

建立 DateTime 物件

在 C# 中建立 DateTime 物件非常簡單。 有多種構造函式可用於以不同參數初始化 DateTime 物件:

// Current date and time
DateTime currentDateTime = DateTime.Now;
// Specific date and time
DateTime specificDateTime = new DateTime(2024, 3, 16, 10, 30, 0);
// Date only
DateTime dateOnly = DateTime.Today;
// Date and time in UTC
DateTime utcDateTime = DateTime.UtcNow;

操作 DateTime 物件

DateTime 物件提供多種方法來操作日期和時間,例如新增或減去時間間隔、提取組件和在時區之間轉換。

DateTime now = DateTime.Now;
// Adding days
DateTime futureDate = now.AddDays(7);
// Subtracting hours
DateTime pastTime = now.AddHours(-3);
// Getting components
int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
// Converting between time zones
DateTime utcTime = DateTime.UtcNow;
DateTime localTime = utcTime.ToLocalTime();

格式化 DateTime 物件

DateTime 物件可以使用各種格式規範符號將其格式化為字串,以便在所需格式中表示。

DateTime dateTime = DateTime.Now;
// Standard date and time format
string standardFormat = dateTime.ToString("G");
// Custom format
string customFormat = dateTime.ToString("dd/MM/yyyy HH:mm:ss");
// Format for sorting
string sortableFormat = dateTime.ToString("yyyy-MM-ddTHH:mm:ss");

比較 DateTime 物件

C# 提供了標準的比較運算子 (<, >, <=, >=, ==, !=),可用於直接比較兩個 DateTime 物件。 這些運算子比較 DateTime 物件的基礎刻度,這代表自西元 1 年 1 月 1 日 00:00:00.000(格里高利曆)以來經過的 100 奈秒間隔的數量。

這是演示使用比較運算子的範例:

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(1);
if (date1 < date2)
{
    Console.WriteLine("date1 is earlier than date2.");
}
else if (date1 > date2)
{
    Console.WriteLine("date1 is later than date2.");
}
else
{
    Console.WriteLine("date1 is equal to date2.");
}

使用 DateTime.Compare C# 方法

除了比較運算子,DateTime 物件還提供方法來比較這些物件之間的相對值。 這些方法在某些情況下提供了更多的靈活性和可讀性。 CompareTo() 方法比較兩個 DateTime 物件,並返回一個整數值,指出其中之一是更早、更晚還是與另一個相同。

DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(1);
int result = date1.CompareTo(date2);
if (result < 0)
{
    Console.WriteLine("date1 is earlier than date2.");
}
else if (result > 0)
{
    Console.WriteLine("date1 is later than date2.");
}
else
{
    Console.WriteLine("date1 is equal to date2.");
}

比較具有容忍度的 DateTime 物件

要比較 DateTime 物件,尤其是在處理涉及時間間隔的計算時,由於潛在的精度差異,考慮容忍水平是很重要的。

這可以通過將兩個 DateTime 值之間的絕對差值與預定的容忍閾值進行比較來實現。

class Program
{
    public static void Main()
    {
        DateTime date1 = DateTime.Now;
        DateTime date2 = DateTime.Now.AddMilliseconds(10);
        TimeSpan tolerance = TimeSpan.FromMilliseconds(5);
        bool isEqual = Math.Abs((date1 - date2).TotalMilliseconds) <= tolerance.TotalMilliseconds;
        if (isEqual)
        {
            Console.WriteLine("date1 is considered equal to date2 within the tolerance.");
        }
        else
        {
            Console.WriteLine("date1 is not equal to date2 within the tolerance.");
        }
    }
}

處理時區和夏令時間

C# 中的 DateTime 物件可以表示本地時間和協調世界時間(UTC)。 在處理全球應用程式時,了解時區轉換非常重要。

DateTime localTime = DateTime.Now;
DateTime utcTime = DateTime.UtcNow;
Console.WriteLine("Local Time: " + localTime);
Console.WriteLine("UTC Time: " + utcTime);

IronPDF to Generate PDF documents in C#

Iron Software 的 IronPDF 是一個高效且易於使用的 PDF 生成程式庫。 您可以使用 NuGet 套件管理器來安裝它:

Datetime Objects in C# (How It Works For Developers): Figure 1

dotnet add package IronPdf --version 2024.3.4

或者從 Visual Studio 如下所示:

Datetime Objects in C# (How It Works For Developers): Figure 2 - Installing IronPDF with the NuGet package manager

現在讓我們深入探討 PDF 生成來示範 DateTime 物件。

using IronPdf;

class Program
{
    static void Main()
    {
        Console.WriteLine("-----------Iron Software-------------");
        
        // Create a new instance of ChromePdfRenderer
        var renderer = new ChromePdfRenderer();
        
        // HTML content for the PDF
        var content = "<h1> Iron Software is Awesome </h1> Made with IronPDF!";
        content += "<h2>Demo Datetime Objects in C#</h2>";
        
        // Current date and time
        content += "<h3>Current date and time</h3>";
        DateTime currentDateTime = DateTime.Now;
        content += $"<p>Current date and time: {currentDateTime:U}</p>";
        Console.WriteLine($"Current date and time: {currentDateTime:U}");
        
        // Specific date and time
        content += "<h3>Specific date and time</h3>";
        DateTime specificDateTime = new DateTime(2024, 3, 16, 10, 30, 0);
        content += $"<p>Specific date and time: {specificDateTime:U}</p>";
        Console.WriteLine($"Specific date and time: {specificDateTime:U}");
        
        // Date only
        content += "<h3>Date Only</h3>";
        DateTime dateOnly = DateTime.Today;
        content += $"<p>Date only: {dateOnly:U}</p>";
        Console.WriteLine($"Date only: {dateOnly:U}");
        
        // Date and time in UTC
        content += "<h3>Date and time in UTC</h3>";
        DateTime utcDateTime = DateTime.UtcNow;
        content += $"<p>Date and time in UTC: {utcDateTime:U}</p>";
        Console.WriteLine($"Date and time in UTC: {utcDateTime:U}");
        
        // Compare dates with Operators
        content += "<h3>Compare dates with Operators</h3>";
        DateTime date1 = DateTime.Now;
        DateTime date2 = DateTime.Now.AddDays(1);
        content += $"<p>Compare date1 {date1:d}, date2 {date2:d}: {CompareDates(date1, date2)}</p>";
        Console.WriteLine($"Compare date1 {date1:U}, date2 {date2:U}: {CompareDates(date1, date2)}");
        
        // Compare dates with Compare Method
        content += "<h3>Compare dates with Compare Method</h3>";
        content += $"<p>Compare date1 {date1:d}, date2 {date2:d}: {CompareDatesWithCompare(date1, date2)}</p>";
        Console.WriteLine($"Compare date1 {date1:U}, date2 {date2:U}: {CompareDatesWithCompare(date1, date2)}");
        
        // Render the content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        
        // Save the PDF to the output file
        pdf.SaveAs("outputDate.pdf");
    }
    
    // Compare two dates using CompareTo method
    public static string CompareDatesWithCompare(DateTime date1, DateTime date2)
    {
        int result = date1.CompareTo(date2);
        string resultString;
        if (result < 0)
        {
            resultString = "date1 is earlier than date2.";
            Console.WriteLine(resultString);
        }
        else if (result > 0)
        {
            resultString = "date1 is later than date2.";
            Console.WriteLine(resultString);
        }
        else
        {
            resultString = "date1 is equal to date2.";
            Console.WriteLine(resultString);
        }
        return resultString;
    }
    
    // Compare two dates using basic comparison operators
    public static string CompareDates(DateTime date1, DateTime date2)
    {
        string result;
        if (CheckLessor(date1, date2))
        {
            result = "date1 is earlier than date2.";
            Console.WriteLine(result);
        }
        else if (CheckGreater(date1, date2))
        {
            result = "date1 is later than date2.";
            Console.WriteLine(result);
        }
        else
        {
            result = "date1 is equal to date2.";
            Console.WriteLine(result);
        }
        return result;
    }
    
    // Helper method to check if the first date is greater than the second date
    public static bool CheckGreater(DateTime date1, DateTime date2)
    {
        return date1 > date2;
    }
    
    // Helper method to check if the first date is less than the second date
    public static bool CheckLessor(DateTime date1, DateTime date2)
    {
        return date1 < date2;
    }
}

以下輸出顯示了使用 DateTime 物件生成的 PDF:

DateTime Objects in C# (How It Works For Developers): Figure 3

IronPDF 試用授權

IronPDF 需要試用授權才能獲得完整功能。 提供一個電子郵件 ID 以生成將發送到您的電子郵件的授權金鑰。

"IronPdf.LicenseKey": "<Your Key>"
JSON

將授權金鑰放入 AppSettings.json 文件中。

結論

C# 中的 DateTime 物件提供瞭在 .NET 應用程式中處理日期和時間的強大方式。 它們提供了一個廣泛的功能集來建立、操作、格式化和比較日期和時間值。 了解如何有效地使用 DateTime 物件對於在 C# 應用程式中構建可靠且準確的日期和時間功能是必須的。

通過利用 DateTime 物件的能力,開發人員可以確保他們的應用程式可以正確處理日期和時間,不論它們遇到的特定需求或情境如何。

無論是計算持續時間、調度任務,還是顯示日期和時間給使用者,DateTime 物件在 C# 程式設計中與日期和時間管理相關的許多方面都扮演著關鍵角色。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立