.NET HELP Datetime Objects in C# (How It Works For Developers) Jacob Mellor 更新:2025年6月22日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 C# 中的 DateTime 物件是在 .NET Framework 應用程式中處理日期和時間的基礎。 這些工具提供了一套強大的功能,可用於處理、格式化和比較日期與時間。 本文旨在提供 C# 中 DateTime 物件的全面概述,涵蓋其建立、操作、格式化和常見用例。 在文章的最後,我們還將探討 Iron Software 的 IronPDF 如何在 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 套件管理程式安裝: dotnet add package IronPdf --version 2024.3.4 或來自 Visual Studio,如下所示: 。 現在讓我們深入 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: 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# 中建立包含 DateTime 資訊的 PDF 文件。您可以在 PDF 內容中插入格式化的 DateTime 字串,以顯示動態時間和日期資料。 如何使用 C# 中的 DateTime 處理夏令時間變更? 日光節約時間可透過使用 ToLocalTime() 將 DateTime 物件轉換為 UTC 或從 UTC 轉換過來,並考慮時區調整,以確保正確的時間表示法,在 C# 中進行管理。 為什麼 DateTime.UtcNow 屬性在 C# 應用程式中很重要? DateTime.UtcNow 屬性提供目前的 UTC 日期和時間,這對於需要一致且不受時區影響的時間參考以進行記錄和資料同步的應用程式來說是非常重要的。 C# 中的 DateTime 物件可以使用自訂格式嗎? 是的,C# 中的 DateTime 物件可透過提供格式字串給 ToString() 方法,使用自訂格式來格式化。這可讓您以任何所需的格式顯示日期和時間。 在 C# 中將 DateTime 物件轉換為字串格式的意義何在? 在 C# 中將 DateTime 物件轉換為字串格式,對於在使用者介面、報表和日誌中顯示日期和時間資訊意義重大。它可以確保資料以可讀且一致的方式呈現。 Jacob Mellor 立即與工程團隊聊天 首席技術長 Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。 相關文章 更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多 更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多 C# Data Structures (How It Works For Developers)C# Tryparse (How It Works For Devel...
更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多
更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多
更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多