Suppose you are working with Date in C#. In that case, there is a possibility you might need to get the difference between two dates in C#, so in this article, I have mentioned how we can find the difference between 2 dates in C# using the Console application.
Using Subtract(-) Operator Method
using System;
namespace CsharpGetDateDifference
{
internal class Program
{
static void Main(string[] args)
{
DateTime pastDate = Convert.ToDateTime("20/06/2022");
DateTime TodayDate = DateTime.Now; // current date is 28/10/2022
var numberOfDays = (TodayDate - pastDate).Days;
var daysInDouble = (TodayDate - pastDate).TotalDays;
Console.WriteLine("Number of days passed after 20/06/2022: " + numberOfDays);
Console.WriteLine("Number of days in double, passed after 20/06/2022: " + daysInDouble);
}
}
}
Output:
Number of days passed after 20/06/2022: 130
Number of days in double, passed after 20/06/2022: 130.85971650194443
In the above code, I have simply used '-
' operator to subtract
pastDate
from todayDate
so we can get total number of days passed.
When we are using '.Days
', it returns total days completed in
int
, while when we are using '.TotalDays
' it returns days as
double
value.
Using DateTime.Subtract() Method
As you can see in the above method we used '-' operator, but instead of using it we can also use DateTime.Subtract() Method in C#, so if we change above example code, it would be as below
using System;
namespace CsharpGetDateDifference
{
internal class Program
{
static void Main(string[] args)
{
DateTime pastDate = Convert.ToDateTime("20/06/2022");
DateTime TodayDate = DateTime.Now; // current date is 28/10/2022
//using .Subtract Method
var numberOfDays = TodayDate.Subtract(pastDate).Days;
var daysInDouble = TodayDate.Subtract(pastDate).TotalDays;
Console.WriteLine("Number of days passed after 20/06/2022: " + numberOfDays);
Console.WriteLine("Number of days in double, passed after 20/06/2022: " + daysInDouble);
}
}
}
Output is same as above
Number of days passed after 20/06/2022: 130
Number of days in double, passed after 20/06/2022: 130.86626161037154
If you want to subtract time from any datetime value, then also you can use DateTime.Subtract()
as DateTime.Subtract(TimeSpan)
returns a new DateTime that subtracts the specified time interval (TimeSpan value) from the current instance.
You may also like to read: