.NET 帮助 DateTime对象在C#中(开发人员如何使用) Jacob Mellor 已更新:2025年6月22日 下载 IronPDF NuGet 下载 DLL 下载 Windows 安装程序 免费试用 LLM副本 LLM副本 将页面复制为 Markdown 格式,用于 LLMs 在 ChatGPT 中打开 向 ChatGPT 咨询此页面 在双子座打开 向 Gemini 询问此页面 在 Grok 中打开 向 Grok 询问此页面 打开困惑 向 Perplexity 询问有关此页面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 复制链接 电子邮件文章 DateTime对象在C#中对于在.NET Framework应用程序中处理日期和时间是基本的。 它们提供了一整套 robust 功能,用于操作、格式化和比较日期和时间。 本文旨在提供关于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对象也提供用于比较这些对象相对值的方法。 在某些场景中,这些方法提供了更灵活性和可读性。 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 处理时区和夏令时 DateTime对象在C#中可以表示本地时间和协调世界时(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对象在C#中(开发人员工作原理):图3 IronPDF 试用许可 IronPDF 需要试用许可才能获得完整功能。 提供一个电子邮件 ID 以生成将发送到您的电子邮箱的许可证密钥。 "IronPdf.LicenseKey": "<Your Key>" 将许可证密钥放在AppSettings.json文件中。 结论 DateTime对象在C#中提供了一种强大的方式来处理.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 对象格式化为字符串? 您可以使用 ToString() 方法和格式说明符在 C# 中将 DateTime 对象格式化为字符串。例如,dateTime.ToString("yyyy-MM-dd") 将日期格式化为 '2023-12-31'。 如何使用 C# 中的 DateTime 将本地时间转换为 UTC? 您可以在 C# 中使用 DateTime 对象上的 ToUniversalTime() 方法将本地时间转换为 UTC。此方法对于跨不同时区标准化日期和时间数据非常有用。 C# 中有哪些方法可以比较 DateTime 对象? 在 C# 中,可以使用 <、>、<=、>=、== 和 != 等运算符比较 DateTime 对象。此外,CompareTo() 方法提供了一种确定两个 DateTime 实例相对顺序的方法。 如何在 C# 中使用 IronPDF 生成包含 DateTime 对象的 PDF 文档? IronPDF 允许开发人员在 C# 中创建包含 DateTime 信息的 PDF 文档。您可以将格式化的 DateTime 字符串插入 PDF 内容中,以显示动态的时间和日期数据。 如何使用 C# 中的 DateTime 处理夏令时的变化? 在 C# 中可以通过将 DateTime 对象与 ToLocalTime() 转换为 UTC,并考虑时区调整来管理夏令时,以确保正确的时间表示。 C# 应用程序中 DateTime.UtcNow 属性为何重要? DateTime.UtcNow 属性提供当前的 UTC 日期和时间,对于需要一致的时区独立时间参考的记录和数据同步的应用程序至关重要。 C# 中的 DateTime 对象可以使用自定义格式进行格式化吗? 是的,可以通过向 ToString() 方法提供格式字符串来使用自定义格式格式化 C# 中的 DateTime 对象。这允许您以任何所需格式显示日期和时间。 在 C# 中将 DateTime 对象转换为字符串格式的意义是什么? 在 C# 中将 DateTime 对象转换为字符串格式对于在用户界面、报告和日志中显示日期和时间信息具有重要意义。它确保数据以可读和一致的方式呈现。 Jacob Mellor 立即与工程团队聊天 首席技术官 Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。 相关文章 已更新2026年2月20日 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多 已更新2025年12月20日 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新2025年12月20日 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 C# 数据结构(开发人员如何使用)C# TryParse(开发人员如何使...
已更新2026年2月20日 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多
已更新2025年12月20日 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多