AIDE .NET

Datetime Objects in C# (How It Works For Developers)

Publié avril 3, 2024
Partager:

Introduction

les objets DateTime en C# sont essentiels pour travailler avec des dates et des heures dans les applications du Framework .NET. Ils offrent un ensemble robuste de fonctionnalités permettant de manipuler, de formater et de comparer des dates et des heures.

Cet article a pour but de fournir une vue d'ensemble des objets DateTime en C#, couvrant leur création, leur manipulation, leur formatage et les cas d'utilisation les plus courants. À la fin de l'article, nous examinerons également commentIronPDF deIron Software peut générer un document PDF à la volée dans les applications C#.

Création d'objets DateTime

La création d'un objet DateTime en C# est simple. Plusieurs constructeurs sont disponibles pour initialiser un objet DateTime avec différents paramètres :

// 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#

Manipulation d'objets DateTime (date et heure)

les objets DateTime fournissent diverses méthodes de manipulation des dates et des heures, telles que l'ajout ou la soustraction d'intervalles de temps, l'extraction de composants et la conversion entre les fuseaux horaires.

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#

Formatage des objets "DateTime

les objets DateTime représentent des heures ou des dates qui peuvent être formatées en chaînes à l'aide de divers spécificateurs de format afin de les représenter dans le format requis.

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#

Comparaison d'objets de type `DateTime

C# fournit des opérateurs de comparaison standard(<, >, <=, >=, ==, !=) qui peut être utilisée pour comparer directement deux objets DateTime. Ces opérateurs comparent les ticks sous-jacents des objets DateTime, qui représentent le nombre d'intervalles de 100 nanosecondes qui se sont écoulés depuis le 1er janvier 0001, à 00:00:00.000 dans le calendrier grégorien.

Voici un exemple illustrant l'utilisation des opérateurs de comparaison :

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#

Utilisation de la méthode C&num ; de DateTime.Compare

En plus des opérateurs de comparaison, les objets DateTime fournissent également des méthodes de comparaison des valeurs relatives entre ces objets. Ces méthodes offrent plus de flexibilité et de lisibilité dans certains scénarios. La fonction CompareTo() compare les objets DateTime sous-jacents pour déterminer le résultat.

Il suppose que les deux dates se situent dans le même fuseau horaire. Après avoir comparé les objets, il renvoie une valeur entière indiquant plus grand, plus petit ou égal. Les valeurs de date identiques renvoient une valeur entière de zéro.

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#

Comparaison d'objets DateTime avec tolérance

Pour comparer des objets DateTime, en particulier lorsqu'il s'agit de calculs impliquant des intervalles de temps, il est important de prendre en compte un niveau de tolérance en raison des différences potentielles de précision.

Pour ce faire, la différence absolue entre deux valeurs DateTime est comparée à un seuil de tolérance prédéfini.

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#

Gestion des fuseaux horaires et de l'heure d'été

les objets DateTime en C# peuvent représenter à la fois l'heure locale et le Temps Universel Coordonné(UTC). Il est important de connaître les conversions de fuseaux horaires, en particulier lorsqu'il s'agit d'applications mondiales.

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 pour générer des documents PDF en C# ;

IronPDF d'Iron Software est une bibliothèque de génération de PDF efficace et facile à utiliser. Nous pouvons l'installer à l'aide du gestionnaire de paquets NuGet

Objets Datetime en C# (Comment ça marche pour les développeurs) : Figure 1

NuGet\Install-Package IronPdf -Version 2024.3.4

Ou à partir de Visual Studio, comme indiqué ci-dessous

Objets Datetime en C#(Comment cela fonctionne-t-il pour les développeurs ?) : Figure 2 - Installation d'IronPDF avec le gestionnaire de paquets NuGet

Nous allons maintenant nous plonger dans la génération de PDF pour faire la démonstration d'un objet 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#

La sortie suivante montre le PDF généré avec des objets DateTime :

les objets `DateTime` en C# (Comment ça marche pour les développeurs) : Figure 3

Licence d'essai d'IronPDF

IronPDF. Fournissez un identifiant e-mail pour générer une clé de licence qui sera ensuite envoyée à l'e-mail que vous avez fourni.

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

Placez la clé de licence dans le fichier AppSettings.Json.

Conclusion

les objets DateTime en C# offrent un moyen puissant de travailler avec des dates et des heures dans les applications .NET. Ils offrent un large éventail de fonctionnalités pour créer, manipuler, formater et comparer des valeurs de date et d'heure. Il est essentiel de comprendre comment utiliser efficacement les objets DateTime pour créer des fonctionnalités de date et d'heure fiables et précises dans les applications C#.

En exploitant les capacités des objets DateTime, les développeurs peuvent s'assurer que leurs applications gèrent correctement les dates et les heures, quels que soient les besoins ou les scénarios spécifiques qu'ils rencontrent.

Qu'il s'agisse de calculer des durées, de planifier des tâches ou d'afficher des dates et des heures aux utilisateurs, les objets DateTime jouent un rôle crucial dans de nombreux aspects de la programmation C# liés à la gestion de la date et de l'heure.

< PRÉCÉDENT
Structures de données C# (Comment ça marche pour les développeurs)
SUIVANT >
C# Tryparse (Comment ça marche pour les développeurs)