.NET 帮助 DateTime对象在C#中(开发人员如何使用) Jacob Mellor 已更新:六月 22, 2025 下载 IronPDF NuGet 下载 DLL 下载 Windows 安装程序 免费试用 法学硕士副本 法学硕士副本 将页面复制为 Markdown 格式,用于 LLMs 在 ChatGPT 中打开 向 ChatGPT 咨询此页面 在双子座打开 向 Gemini 询问此页面 在 Grok 中打开 向 Grok 询问此页面 打开困惑 向 Perplexity 询问有关此页面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 复制链接 电子邮件文章 DateTime 对象在 C# 中对于在 .NET Framework 应用程序中处理日期和时间是基本的。 它们提供了一整套 robust 功能,用于操作、格式化和比较日期和时间。 本文旨在提供 DateTime 对象在 C# 中的综合概述,涵盖其创建、操作、格式化和常见使用案例。 在文章的结尾,我们还将探讨如何使用 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 对象的底层 tick,它们表示自公历 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# 中的 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 文件中。 结论 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 拥有曼彻斯特大学 (1998-2001) 的一级荣誉土木工程学士学位。1999 年在伦敦创办了自己的第一家软件公司,并于 2005 年创建了他的第一个 .NET 组件后,他专注于解决微软生态系统中的复杂问题。他的旗舰 IronPDF 和 Iron Suite .NET 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。 相关文章 已更新十二月 11, 2025 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多 已更新十二月 20, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新十二月 20, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 C# 数据结构(开发人员如何使用)C# TryParse(开发人员如何使...
已更新十二月 11, 2025 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多
已更新十二月 20, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多