C#のDatetime Objects(開発者向けの動作方法)
DateTime オブジェクトは、C# において、.NET Frameworkアプリケーションで日時を扱う際の基本です。 それらは、日付と時刻を操作、フォーマット、および比較するための強力な機能を提供します。
この記事は、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
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' 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.UtcNowDateTime オブジェクトの操作
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()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()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")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")DateTime オブジェクトの比較
C# では、標準の比較演算子(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 IfDim 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 IfDateTime.Compare C# メソッドの使用
比較演算子に加え、DateTime オブジェクトは、それらのオブジェクト間の相対的な値の比較を行うためのメソッドも提供します。 これらのメソッドは、特定の状況でより柔軟性と可読性を提供します。 CompareTo() メソッドは、2つの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 IfDim 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 IfDateTime オブジェクトの許容誤差を考慮した比較
特に時間間隔を含む計算を扱う際に、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 ClassFriend 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タイムゾーンと夏時間の取り扱い
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)Dim localTime As DateTime = DateTime.Now
Dim utcTime As DateTime = DateTime.UtcNow
Console.WriteLine("Local Time: " & localTime)
Console.WriteLine("UTC Time: " & utcTime)IronPDF to Generate PDF documents in C#
IronPDF は、Iron Software からの効率的で使いやすい PDF 生成ライブラリです。 NuGet パッケージ マネージャーを使用してインストールできます。

または、以下に示すように Visual Studio から直接インストールできます。

では、DateTime オブジェクトをデモするための PDF 生成に進みましょう。
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;
}
}Imports IronPdf
Class Program
Shared Sub Main()
Console.WriteLine("-----------Iron Software-------------")
' Create a new instance of ChromePdfRenderer
Dim renderer = New ChromePdfRenderer()
' HTML content for the PDF
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 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>"
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}: {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
Dim pdf = renderer.RenderHtmlAsPdf(content)
' Save the PDF to the output file
pdf.SaveAs("outputDate.pdf")
End Sub
' Compare two dates using CompareTo method
Public Shared Function CompareDatesWithCompare(date1 As DateTime, 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
' Compare two dates using basic comparison operators
Public Shared Function CompareDates(date1 As DateTime, 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
' Helper method to check if the first date is greater than the second date
Public Shared Function CheckGreater(date1 As DateTime, date2 As DateTime) As Boolean
Return date1 > date2
End Function
' Helper method to check if the first date is less than the second date
Public Shared Function CheckLessor(date1 As DateTime, date2 As DateTime) As Boolean
Return date1 < date2
End Function
End ClassImports IronPdf
Class Program
Shared Sub Main()
Console.WriteLine("-----------Iron Software-------------")
' Create a new instance of ChromePdfRenderer
Dim renderer = New ChromePdfRenderer()
' HTML content for the PDF
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 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>"
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}: {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
Dim pdf = renderer.RenderHtmlAsPdf(content)
' Save the PDF to the output file
pdf.SaveAs("outputDate.pdf")
End Sub
' Compare two dates using CompareTo method
Public Shared Function CompareDatesWithCompare(date1 As DateTime, 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
' Compare two dates using basic comparison operators
Public Shared Function CompareDates(date1 As DateTime, 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
' Helper method to check if the first date is greater than the second date
Public Shared Function CheckGreater(date1 As DateTime, date2 As DateTime) As Boolean
Return date1 > date2
End Function
' Helper method to check if the first date is less than the second date
Public Shared Function CheckLessor(date1 As DateTime, date2 As DateTime) As Boolean
Return date1 < date2
End Function
End Class次の出力は、DateTime オブジェクトで生成されたPDFを示しています。
DateTime Objects in C# (開発者向けの動作方法): 図3
IronPDF トライアル ライセンス
IronPDF は、完全な機能を利用するためにトライアル ライセンスが必要です。 ライセンスキーを生成するためにメール ID を提供すると、メールでライセンスキーが送信されます。
"IronPdf.LicenseKey": "<Your Key>"
ライセンスキーをAppSettings.json ファイルに配置してください。
結論
C# の DateTime オブジェクトは、.NET アプリケーションで日時を扱う強力な方法を提供します。 それらは、日付と時刻の作成、操作、フォーマット、比較の幅広い機能を提供します。 DateTime オブジェクトを効果的に使用する方法を理解することは、C# アプリケーションにおける信頼性の高い正確な日時機能を構築するために非常に重要です。
DateTime オブジェクトの能力を活用することで、開発者は、特定の要件やシナリオに関係なく、アプリケーションが日時を正しく処理することを保証できます。
期間の計算、タスクのスケジューリング、ユーザーへの日時の表示に関わらず、DateTime オブジェクトは、C#プログラミングにおける日時管理に関連する多くの側面で重要な役割を果たします。
ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。