.NET 幫助

C# 中的日期時間對象(開發人員如何使用)

發佈 2024年4月3日
分享:

介紹

在 C# 中,DateTime 物件是處理 .NET Framework 應用程式中的日期和時間的基礎。 他們提供強大的功能集,用於操作、格式化和比較日期和時間。

本文旨在提供 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;
// 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 物件還提供用於比較這些物件之間相對值的方法。 這些方法在某些情況下提供了更多的靈活性和可讀性。 CompareTo()方法比較底層的 DateTime 物件以確定結果。

假设这两个日期处于相同的时区值。 在比較物件之後,它返回一個整數值,表示大於、小於或等於。 相同日期值返回整數值 0。

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 物件可以表示本地時間和協調世界時間 (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);
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# 中生成 PDF 文件

IronPDF 是 Iron Software 所提供的高效且易於使用的 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. 請提供電子郵件地址以生成授權密鑰,該密鑰將發送到您提供的電子郵件。

"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 檔案中。

結論

在 .NET 應用程式中,DateTime 物件在 C# 中提供了一個強大的方式來處理日期和時間。 他們提供廣泛的功能來創建、操作、格式化和比較日期和時間值。 理解如何有效使用 DateTime 對象對於構建可靠且精確的日期和時間功能在 C# 應用中至關重要。

通過利用 DateTime 對象的功能,開發人員可以確保他們的應用程式能夠正確處理日期和時間,無論其遇到的具體需求或情境如何。

無論是計算持續時間、排程任務,還是向用戶顯示日期和時間,DateTime 對象在許多與 C# 程式設計中的日期和時間管理相關的方面都起著關鍵作用。

< 上一頁
C# 資料結構(開發人員的運作方式)
下一個 >
C# Tryparse(對開發人員的運作方式)

準備開始了嗎? 版本: 2024.12 剛剛發布

免費 NuGet 下載 總下載次數: 11,622,374 查看許可證 >