IRONSOFTWAREHOME
开发者更新

DateTime对象在C#中(开发人员如何使用)

Jacob Mellor,Team Iron 的首席技术官
Jacob Mellor
Updated: 2026年4月23日

DateTime 对象在C#中是处理.NET Framework应用程序中日期和时间的基础。 它们提供了一整套 robust 功能,用于操作、格式化和比较日期和时间。

本文旨在全面概述C#中DateTime 对象,涵盖其创建、操作、格式化及常见使用案例。 在文章的结尾,我们还将探讨如何使用 IronPDFIron 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;

操作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 对象

可以使用多种格式说明符将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 对象

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.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 对象

比较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.");
        }
    }
}

处理时区和夏令时

C#中的DateTime 对象可以表示本地时间和协调世界时 (UTC)。 了解时区转换是重要的,特别是在处理全球应用程序时。

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

IronPDF to Generate PDF documents in C#

来自 Iron Software 的 IronPDF 是一个高效且易于使用的 PDF 生成库。 您可以使用 NuGet 包管理器安装它:

C# 中的日期时间对象(开发者如何使用):图1

dotnet add package IronPdf --version 2024.3.4

或从如下所示的 Visual Studio 安装它:

C# 中的日期时间对象(开发者如何使用):图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;
    }
}

以下输出显示使用DateTime 对象生成的PDF:

DateTime 对象在C#中(开发者如何使用):图3

IronPDF 试用许可

IronPDF 需要试用许可才能获得完整功能。 提供一个电子邮件 ID 以生成将发送到您的电子邮箱的许可证密钥。

"IronPdf.LicenseKey": "<Your Key>"
JSON

将许可证密钥放置在AppSettings.json 文件中。

结论

C#中的DateTime 对象为在.NET应用程序中处理日期和时间提供了一种强大的方法。 它们提供了广泛的功能来创建、操作、格式化和比较日期和时间值。 了解如何有效地使用DateTime 对象对在C#应用程序中构建可靠且准确的日期和时间功能至关重要。

通过利用DateTime 对象的功能,开发人员可以确保其应用程序能够正确处理日期和时间,无论他们遇到的具体要求或场景如何。

无论是计算持续时间、调度任务,还是向用户显示日期和时间,DateTime 对象在C#编程中与日期和时间管理相关的许多方面都起着关键作用。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

OR
bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户
C# 用于 PDF 的 NuGet 库
通过 NuGet 安装

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解决方案资源管理器中,右键点击引用,管理 NuGet 包
  2. 选择浏览并搜索 “IronPDF”
  3. 选择包并安装
C# PDF DLL
下载 DLL

版本: 2026.9

或在此处下载 Windows 安装程序。

  1. 下载并解压 IronPDF 到您的解决方案目录中的 ~/Libs 之类的位置
  2. 在 Visual Studio 解决方案资源管理器中,右键点击引用。选择浏览,“IronPDF.dll”

$999