.NET幫助 C# 中的 DateTime 對象(對於開發者的運行原理) Jacob Mellor 更新:2025年6月22日 下載 IronPDF NuGet 下載 DLL 下載 Windows Installer 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 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; // 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 to Generate PDF documents in C# 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: DateTime Objects in C# (How It Works For Developers): Figure 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 物件。 如何將 DateTime 物件格式化為 C# 中的字符串? 您可以在 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 文件。您可以將格式化的 DateTime 字符串插入到 PDF 內容中,以顯示動態是時間和日期數據。 如何使用 C# 的 DateTime 處理夏令時間變化? 可以通過使用 ToLocalTime() 將 DateTime 物件與 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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。 相關文章 更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新2025年12月20日 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# 數據結構(對於開發者的運行原理)C# Tryparse(對於開發者的運...
更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多