.NET 帮助

C# 中的日期时间对象(开发人员的使用方法)

发布 2024年四月3日
分享:

简介

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

本文旨在全面介绍 C# 中的 DateTime 对象,包括其创建、操作、格式化和常见用例。在文章的最后,我们还将探讨如何 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;
' Current date and time
Dim currentDateTime As DateTime = DateTime.Now
' Specific date and time
Dim specificDateTime As New DateTime(2024, 3, 16, 10, 30, 0)
' Date only
Dim dateOnly As DateTime = DateTime.Today
' Date and time in UTC
Dim utcDateTime As DateTime = DateTime.UtcNow
VB   C#

操作 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();
Dim now As DateTime = DateTime.Now
' Adding days
Dim futureDate As DateTime = now.AddDays(7)
' Subtracting hours
Dim pastTime As DateTime = now.AddHours(-3)
' Getting components
Dim year As Integer = now.Year
Dim month As Integer = now.Month
Dim day As Integer = now.Day
Dim hour As Integer = now.Hour
Dim minute As Integer = now.Minute
Dim second As Integer = now.Second
' Converting between time zones
Dim utcTime As DateTime = DateTime.UtcNow
Dim localTime As DateTime = utcTime.ToLocalTime()
VB   C#

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");
Imports System

Dim dateTime As DateTime = DateTime.Now
' Standard date and time format
Dim standardFormat As String = dateTime.ToString("G")
' Custom format
Dim customFormat As String = dateTime.ToString("dd/MM/yyyy HH:mm:ss")
' Format for sorting
Dim sortableFormat As String = dateTime.ToString("yyyy-MM-ddTHH:mm:ss")
VB   C#

比较 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.");
}
Dim date1 As DateTime = DateTime.Now
Dim date2 As DateTime = DateTime.Now.AddDays(1)
If date1 < date2 Then
	Console.WriteLine("date1 is earlier than date2.")
ElseIf date1 > date2 Then
	Console.WriteLine("date1 is later than date2.")
Else
	Console.WriteLine("date1 is equal to date2.")
End If
VB   C#

使用 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.");
}
Dim date1 As DateTime = DateTime.Now
Dim date2 As DateTime = DateTime.Now.AddDays(1)
Dim result As Integer = date1.CompareTo(date2)
If result < 0 Then
	Console.WriteLine("date1 is earlier than date2.")
ElseIf result > 0 Then
	Console.WriteLine("date1 is later than date2.")
Else
	Console.WriteLine("date1 is equal to date2.")
End If
VB   C#

使用公差比较 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.");
}
}
}
Friend Class Program
	Public Shared Sub Main()
Dim date1 As DateTime = DateTime.Now
Dim date2 As DateTime = DateTime.Now.AddMilliseconds(10)
Dim tolerance As TimeSpan = TimeSpan.FromMilliseconds(5)
Dim isEqual As Boolean = Math.Abs((date1.Subtract(date2)).TotalMilliseconds) <= tolerance.TotalMilliseconds
If isEqual Then
	Console.WriteLine("date1 is considered equal to date2 within the tolerance.")
Else
	Console.WriteLine("date1 is not equal to date2 within the tolerance.")
End If
	End Sub
End Class
VB   C#

处理时区和夏令时

C#中的 "DateTime "对象既可以表示本地时间,也可以表示协调世界时 (世界协调时).注意时区转换非常重要,尤其是在处理全球应用程序时。

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);
Dim localTime As DateTime = DateTime.Now
Dim utcTime As DateTime = DateTime.UtcNow
Console.WriteLine("Local Time: " & localTime)
Console.WriteLine("UTC Time: " & utcTime)
VB   C#

IronPDF 以 C&num 生成 PDF 文档;

Iron Software 的 IronPDF 是一款高效易用的 PDF 生成库。我们可以使用 NuGet 软件包管理器安装它

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

NuGet\Install-Package IronPdf -Version 2024.3.4

或从 Visual Studio 安装,如下所示

C# 中的日期时间对象(开发人员如何使用):图 2 - 使用 NuGet 软件包管理器安装 IronPDF

现在,让我们深入 PDF 生成,演示 DateTime 对象。

class Program
{
    static void Main()
    {
        Console.WriteLine("-----------Iron Software-------------");
        var renderer = new ChromePdfRenderer(); // var pattern
        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 only: {dateOnly:U}</p>";
        Console.WriteLine($"Date only: {dateOnly: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}: {dateOnly:U}");
        //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}: {dateOnly:U}");
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs("outputDate.pdf"); // Saves PDF
    }
    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;
    }
    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;
    }
    public static bool CheckGreater(DateTime date1, DateTime date2)
    {
        return date1 > date2;
    }
    public static bool CheckLessor(DateTime date1, DateTime date2)
    {
        return date1 < date2;
    }
}
class Program
{
    static void Main()
    {
        Console.WriteLine("-----------Iron Software-------------");
        var renderer = new ChromePdfRenderer(); // var pattern
        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 only: {dateOnly:U}</p>";
        Console.WriteLine($"Date only: {dateOnly: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}: {dateOnly:U}");
        //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}: {dateOnly:U}");
        var pdf = renderer.RenderHtmlAsPdf(content);
        pdf.SaveAs("outputDate.pdf"); // Saves PDF
    }
    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;
    }
    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;
    }
    public static bool CheckGreater(DateTime date1, DateTime date2)
    {
        return date1 > date2;
    }
    public static bool CheckLessor(DateTime date1, DateTime date2)
    {
        return date1 < date2;
    }
}
Friend Class Program
	Shared Sub Main()
		Console.WriteLine("-----------Iron Software-------------")
		Dim renderer = New ChromePdfRenderer() ' var pattern
		Dim 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>"
		Dim currentDateTime As DateTime = 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>"
		Dim specificDateTime As 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>"
		Dim dateOnly As DateTime = 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>"
		Dim utcDateTime As DateTime = DateTime.UtcNow
		content &= $"<p>Date only: {dateOnly:U}</p>"
		Console.WriteLine($"Date only: {dateOnly:U}")
		'Compare dates with Operators
		content &= "<h3>Compare dates with Operators</h3>"
		Dim date1 As DateTime = DateTime.Now
		Dim date2 As DateTime = 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}: {dateOnly:U}")
		'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}: {dateOnly:U}")
		Dim pdf = renderer.RenderHtmlAsPdf(content)
		pdf.SaveAs("outputDate.pdf") ' Saves PDF
	End Sub
	Public Shared Function CompareDatesWithCompare(ByVal date1 As DateTime, ByVal date2 As DateTime) As String
		Dim result As Integer = date1.CompareTo(date2)
		Dim resultString As String
		If result < 0 Then
			resultString = "date1 is earlier than date2."
			Console.WriteLine(resultString)
		ElseIf result > 0 Then
			resultString = "date1 is later than date2."
			Console.WriteLine(resultString)
		Else
			resultString = "date1 is equal to date2."
			Console.WriteLine(resultString)
		End If
		Return resultString
	End Function
	Public Shared Function CompareDates(ByVal date1 As DateTime, ByVal date2 As DateTime) As String
		Dim result As String
		If CheckLessor(date1, date2) Then
			result = "date1 is earlier than date2."
			Console.WriteLine(result)
		ElseIf CheckGreater(date1, date2) Then
			result = "date1 is later than date2."
			Console.WriteLine(result)
		Else
			result = "date1 is equal to date2."
			Console.WriteLine(result)
		End If
		Return result
	End Function
	Public Shared Function CheckGreater(ByVal date1 As DateTime, ByVal date2 As DateTime) As Boolean
		Return date1 > date2
	End Function
	Public Shared Function CheckLessor(ByVal date1 As DateTime, ByVal date2 As DateTime) As Boolean
		Return date1 < date2
	End Function
End Class
VB   C#

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

C# 中的 `DateTime` 对象(开发人员如何使用):图 3

IronPDF 试用许可证

IronPDF.提供电子邮件 ID 以生成许可证密钥,然后将其发送到您提供的电子邮件中。

"IronPDF.LicenseKey": "<Your Key>"
"IronPDF.LicenseKey": "<Your Key>"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPDF.LicenseKey": "<Your Key>"
VB   C#

将许可证密钥放入 AppSettings.Json 文件。

结论

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

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

无论是计算工期、安排任务,还是向用户显示日期和时间,DateTime 对象都在 C# 编程中与日期和时间管理相关的许多方面发挥着至关重要的作用。

< 前一页
C# 数据结构(开发人员如何使用)
下一步 >
C# Tryparse(开发人员如何使用)

准备开始了吗? 版本: 2024.10 刚刚发布

免费NuGet下载 总下载量: 11,108,738 查看许可证 >