get days difference between two datetime in csharp

To get the difference in days between two DateTime values in C#, you can use the TimeSpan object. Here is an example code:

main.cs
DateTime date1 = new DateTime(2021, 6, 1);
DateTime date2 = new DateTime(2021, 6, 10);

TimeSpan difference = date2 - date1;
int days = difference.Days;

Console.WriteLine("Days difference between {0} and {1} is {2} days", date1, date2, days);
244 chars
8 lines

In this example, we have two DateTime objects 'date1' and 'date2' representing the dates between which we want to calculate the difference. We create a TimeSpan object by subtracting 'date1' from 'date2'. The 'Days' property of the TimeSpan object gives us the number of days in the difference.

The output of the above code will be:

main.cs
Days difference between 6/1/2021 12:00:00 AM and 6/10/2021 12:00:00 AM is 9 days
81 chars
2 lines

gistlibby LogSnag