Test in einer Live-Umgebung
Test in der Produktion ohne Wasserzeichen.
Funktioniert überall, wo Sie es brauchen.
dateTime"-Objekte in C# sind grundlegend für die Arbeit mit Datums- und Zeitangaben in .NET-Framework-Anwendungen. Sie bieten einen robusten Satz von Funktionen zum Bearbeiten, Formatieren und Vergleichen von Daten und Zeiten.
Dieser Artikel soll einen umfassenden Überblick über DateTime
-Objekte in C# geben, der ihre Erstellung, Manipulation, Formatierung und allgemeine Anwendungsfälle abdeckt. Am Ende des Artikels werden wir auch untersuchen, wie IronPDF von Iron Software kann in C#-Anwendungen ein PDF-Dokument im Handumdrehen erzeugen.
Das Erstellen eines DateTime
-Objekts in C# ist einfach. Es gibt mehrere Konstruktoren, um ein DateTime
-Objekt mit verschiedenen Parametern zu initialisieren:
// 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
DateTime
-ObjektendateTime"-Objekte bieten verschiedene Methoden zur Bearbeitung von Datums- und Zeitangaben, wie das Addieren oder Subtrahieren von Zeitintervallen, das Extrahieren von Komponenten und das Konvertieren zwischen Zeitzonen.
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()
DateTime
-ObjektendateTime"-Objekte stellen Zeiten oder Daten dar, die mit Hilfe verschiedener Formatspezifikationen in Strings formatiert werden können, um sie im gewünschten Format darzustellen.
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")
DateTime
-ObjektenC# bietet Standard-Vergleichsoperatoren (<
, >
, <=
, >=
, ==
, !=
) die verwendet werden kann, um zwei DateTime
-Objekte direkt zu vergleichen. Diese Operatoren vergleichen die zugrunde liegenden Ticks der `DateTime'-Objekte, die die Anzahl der 100-Nanosekunden-Intervalle darstellen, die seit dem 1. Januar 0001 um 00:00:00.000 im gregorianischen Kalender verstrichen sind.
Hier ist ein Beispiel, das die Verwendung von Vergleichsoperatoren zeigt:
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
DateTime.Compare
C#Zusätzlich zu den Vergleichsoperatoren bieten DateTime
-Objekte auch Methoden für den Vergleich der relativen Werte zwischen diesen Objekten. Diese Methoden bieten in bestimmten Szenarien mehr Flexibilität und Lesbarkeit. Die Funktion "Vergleichen bis()methode vergleicht die zugrunde liegenden "DateTime"-Objekte, um das Ergebnis zu ermitteln.
Es wird davon ausgegangen, dass die beiden Daten in der gleichen Zeitzone liegen. Nach dem Vergleich der Objekte wird ein ganzzahliger Wert zurückgegeben, der größer, kleiner oder gleich ist. Gleiche Datumswerte ergeben den ganzzahligen Wert Null.
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
Beim Vergleich von `DateTime'-Objekten, insbesondere bei Berechnungen mit Zeitintervallen, ist es wichtig, eine Toleranzschwelle aufgrund möglicher Unterschiede in der Genauigkeit zu berücksichtigen.
Dies kann erreicht werden, indem die absolute Differenz zwischen zwei "DateTime"-Werten mit einer vordefinierten Toleranzschwelle verglichen wird.
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
dateTime"-Objekte in C# können sowohl die Ortszeit als auch die koordinierte Weltzeit darstellen (UTC). Es ist wichtig, sich der Zeitzonenumstellung bewusst zu sein, vor allem, wenn es um globale Anwendungen geht.
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)
IronPDF von Iron Software ist eine effiziente und einfach zu bedienende Bibliothek zur PDF-Erzeugung. Wir können es mit dem NuGet-Paketmanager installieren
NuGet\Install-Package IronPdf -Version 2024.3.4
Oder von Visual Studio aus wie unten gezeigt
Lassen Sie uns nun in die PDF-Erzeugung eintauchen, um ein DateTime-Objekt zu demonstrieren.
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
Die folgende Ausgabe zeigt das mit DateTime
-Objekten erzeugte PDF:
IronPDF. Geben Sie eine E-Mail-ID an, um einen Lizenzschlüssel zu generieren, der dann an die von Ihnen angegebene E-Mail-Adresse gesendet wird.
"IronPDF.LicenseKey": "<Your Key>"
"IronPDF.LicenseKey": "<Your Key>"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPDF.LicenseKey": "<Your Key>"
Platzieren Sie den Lizenzschlüssel in der Datei AppSettings.Json.
dateTime"-Objekte in C# bieten eine leistungsstarke Möglichkeit, mit Datums- und Zeitangaben in .NET-Anwendungen zu arbeiten. Sie bieten eine breite Palette von Funktionen zur Erstellung, Bearbeitung, Formatierung und zum Vergleich von Datums- und Zeitwerten. Das Verständnis der effektiven Verwendung von DateTime
-Objekten ist für die Erstellung zuverlässiger und genauer Datums- und Zeitfunktionen in C#-Anwendungen unerlässlich.
Durch die Nutzung der Fähigkeiten von "DateTime"-Objekten können Entwickler sicherstellen, dass ihre Anwendungen Datums- und Zeitangaben korrekt verarbeiten, unabhängig von den spezifischen Anforderungen oder Szenarien, denen sie begegnen.
Ob es sich um die Berechnung von Zeiträumen, die Planung von Aufgaben oder die Anzeige von Daten und Zeiten für Benutzer handelt, DateTime
-Objekte spielen eine entscheidende Rolle in vielen Aspekten der C#-Programmierung im Zusammenhang mit der Datums- und Zeitverwaltung.
9 .NET API-Produkte für Ihre Bürodokumente