📅  最后修改于: 2023-12-03 15:13:48.727000             🧑  作者: Mango
In C#, the DateTime
class provides a way to perform various date and time arithmetic operations. One common use case is to calculate the difference between two dates in minutes.
The TimeSpan
structure represents a time interval, and can be used to calculate the difference between two dates. To calculate the difference in minutes, you can use the TotalMinutes
property of the TimeSpan
object returned by the Subtract
method.
Here is a C# code snippet that demonstrates how to calculate the difference between two dates in minutes:
DateTime date1 = new DateTime(2021, 7, 1, 8, 0, 0);
DateTime date2 = new DateTime(2021, 7, 1, 9, 30, 0);
TimeSpan diff = date2.Subtract(date1);
int diffInMinutes = (int)diff.TotalMinutes;
Console.WriteLine("The difference in minutes is: " + diffInMinutes);
In this example, we have two DateTime
objects date1
and date2
, representing two dates. We then calculate the difference between the two dates using the Subtract
method, which returns a TimeSpan
object representing the time interval between the two dates. Finally, we use the TotalMinutes
property of the TimeSpan
object to get the difference in minutes, which is then cast to an integer and printed to the console.
This code snippet would output the following:
The difference in minutes is: 90
In summary, calculating the difference between two dates in minutes in C# can be achieved by using the TimeSpan
structure and its TotalMinutes
property.