跳至頁尾內容
.NET 幫助

C# 中的日期時間物件(開發者如何理解它)

C# 中的 DateTime 物件是在 .NET Framework 應用程式中處理日期和時間的基礎。 這些工具提供了一套強大的功能,可用於處理、格式化和比較日期與時間。

本文旨在提供 C# 中 DateTime 物件的全面概述,涵蓋其建立、操作、格式化和常見用例。 在文章的最後,我們還將探討 Iron SoftwareIronPDF 如何在 C# 應用程式中即時產生 PDF 文件。

建立日期時間物件

在 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;
// 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;
$vbLabelText   $csharpLabel

操作 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 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();
$vbLabelText   $csharpLabel

格式化 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 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");
$vbLabelText   $csharpLabel

比較 DateTime 物件

C# 提供了標準的比較運算符號 (<, >, <=, >=, ==, !=) 可直接用來比較兩個 DateTime 物件。 這些運算符號會比較 DateTime 物件的底層刻度,這些刻度代表自 0001 年 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 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.");
}
$vbLabelText   $csharpLabel

使用 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 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.");
}
$vbLabelText   $csharpLabel

使用公差比較 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.");
        }
    }
}
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.");
        }
    }
}
$vbLabelText   $csharpLabel

處理時區和夏令時間

C# 中的 DateTime 物件可以代表當地時間和世界協調時間 (UTC)。 必須注意時區轉換,尤其是在處理全球應用程式時。

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

IronPDF 以 C# 和 num 生成 PDF 文件;

Iron Software 的 IronPDF 是一款高效且易用的 PDF 生成库。 您可以使用 NuGet 套件管理程式安裝:

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

dotnet add package IronPdf --version 2024.3.4

或來自 Visual Studio,如下所示:

Datetime Objects in C# (How It Works For Developers):圖 2 - 使用 NuGet 套件管理程式安裝 IronPDF

現在讓我們深入 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;
    }
}
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;
    }
}
$vbLabelText   $csharpLabel

以下輸出顯示以 DateTime 物件產生的 PDF:

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

IronPDF 試用授權。

IronPDF需要試用授權才能使用完整功能。 提供電子郵件 ID 以產生授權金鑰,該金鑰將傳送至您的電子郵件。

"IronPDF.LicenseKey": "<Your Key>"

將授權金鑰放入 AppSettings.json 檔案中。

結論

C# 中的 DateTime 物件提供了在 .NET 應用程式中處理日期和時間的強大方式。 這些工具提供廣泛的功能,可用於建立、處理、格式化及比較日期與時間值。 瞭解如何有效地使用 DateTime 物件,對於在 C# 應用程式中建立可靠且精確的日期與時間功能至關重要。

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

無論是計算工期、排程任務或向使用者顯示日期和時間,DateTime 物件在 C# 程式設計中與日期和時間管理相關的許多方面都扮演著重要的角色。

常見問題解答

C# 中的 DateTime 物件是用來做什麼的?

C# 中的 DateTime 物件用於在 .NET Framework 應用程式中處理日期和時間。它們提供了操作、格式化和比較日期和時間的功能,因此對於任何處理時間資料的應用程式都至關重要。

如何在 C# 中建立特定日期的 DateTime 物件?

要在 C# 中為特定日期建立 DateTime 對象,可以使用帶有參數的建構子。例如,` DateTime specificDate = new DateTime(2023, 12, 31);將建立一個日期為 2023 年 12 月 31 日的 DateTime 物件。

如何在 C# 中將 DateTime 物件格式化為字串?

在 C# 中,您可以使用帶有格式說明符的ToString()方法將 DateTime 物件格式化為字串。例如, dateTime.ToString("yyyy-MM-dd")會將日期格式化為 '2023-12-31'。

如何在 C# 中使用 DateTime 將本地時間轉換為 UTC 時間?

在 C# 中,您可以使用 DateTime 物件的ToUniversalTime()方法將本機時間轉換為 UTC 時間。這對於跨不同時區標準化日期和時間資料非常有用。

C#中有哪些方法可以用來比較DateTime物件?

在 C# 中,可以使用諸如 <、>、<=、>=、== 和 != 之類的運算子來比較 DateTime 物件。此外, CompareTo()方法提供了一種確定兩個 DateTime 實例相對順序的方法。

如何使用 IronPDF 在 C# 中產生包含 DateTime 物件的 PDF 文件?

IronPDF 讓開發人員可以使用 C# 建立包含日期時間資訊的 PDF 文件。您可以將格式化的日期時間字串插入 PDF 內容中,以顯示動態的時間和日期資料。

在 C# 中使用 DateTime 處理夏令時變更時,該如何處理?

在 C# 中,可以透過使用ToLocalTime()將 DateTime 物件轉換為 UTC 和從 UTC 轉換來管理夏令時,並考慮時區調整以確保正確的時間表示。

為什麼 DateTime.UtcNow 屬性在 C# 應用程式中很重要?

DateTime.UtcNow 屬性提供當前的 UTC 日期和時間,這對於需要一致且與時區無關的時間參考以進行日誌記錄和資料同步的應用程式至關重要。

C# 中的 DateTime 物件可以使用自訂格式進行格式化嗎?

是的,C# 中的 DateTime 物件可以透過向ToString()方法提供格式字串來使用自訂格式進行格式化。這樣,您就可以以任何所需的格式顯示日期和時間。

在 C# 中將 DateTime 物件轉換為字串格式有何意義?

在 C# 中將 DateTime 物件轉換為字串格式對於在使用者介面、報表和日誌中顯示日期和時間資訊至關重要。它能確保數據以易於閱讀且一致的方式呈現。

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。