.NET ヘルプ

C#における日時オブジェクト (開発者向けの仕組み)

更新済み 4月 3, 2024
共有:

イントロダクション

C#のDateTimeオブジェクトは、.NET Frameworkアプリケーションで日付と時刻を扱うための基礎的な要素です。 それらは、日付と時刻の操作、書式設定、および比較のための強力な機能セットを提供します。

この記事は、C#におけるDateTimeオブジェクトの生成、操作、書式設定、一般的な使用例を網羅的に解説することを目的としています。 記事の最後に、どのようにして... IronPDF から アイアンソフトウェア 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# は標準の比較演算子を提供します (<, >, <=, >=, ==,!=) 2つのDateTimeオブジェクトを直接比較するために使用することができます。 これらの演算子は、DateTime` オブジェクトの基礎となるティックを比較します。このティックは、グレゴリオ暦の紀元1年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メソッドは、基になる型の値を比較するために使用されます。このメソッドは、指定されたオブジェクトと現在のインスタンスを比較し、オブジェクトの順序を示す整数を返します。使用方法としては、例えば数値型や文字列型の比較に用いられます。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.");
}
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 オブジェクトを比較する際、特に時間間隔に関わる計算を行う場合、精度の差による可能性を考慮して許容レベルを考慮することが重要です。

これは、2つの 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#

C#でPDFドキュメントを生成するためのIronPDF

Iron SoftwareによるIronPDFは、効率的で使いやすいPDF生成ライブラリです。 NuGetパッケージマネージャーを使用してインストールできます。

C#でのDatetimeオブジェクト(開発者向けの動作方法):図1

NuGet\Install-Package IronPdf -Version 2024.3.4

以下に示すようにVisual Studioから

C# における日時オブジェクト(開発者のための動作方法):図 2 - NuGet パッケージマネージャーでの IronPDF のインストール

それでは、DateTimeオブジェクトのデモとしてPDF生成に取り掛かりましょう。

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ファイルにライセンスキーを配置してください。

結論

C#のDateTimeオブジェクトは、.NETアプリケーションで日付と時刻を操作する強力な方法を提供します。 彼らは、日付と時間の値の作成、操作、フォーマット、比較のための幅広い機能を提供しています。 C#アプリケーションで信頼性があり、正確な日付と時刻の機能を構築するためには、DateTimeオブジェクトを効果的に使用する方法を理解することが重要です。

DateTimeオブジェクトの機能を活用することで、開発者は、特定の要件や遭遇するシナリオにかかわらず、アプリケーションが日付と時間を正しく処理することを保証できます。

計算する期間、タスクのスケジューリング、またはユーザーに日付と時間を表示する場合、DateTimeオブジェクトは日付と時間の管理に関連するC#プログラミングの多くの側面において重要な役割を果たします。

< 以前
C# データ構造 (開発者向けの仕組み)
次へ >
C# TryParse(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >