In this article, you will learn how to compare two dates without time in C#. Sometimes, we need to compare only the date parts of two DateTime variables in C#. So here in this article, we used the ==
operator and .CompareTo()
method to compare the two dates without time in C#.
Here are the examples to compare two dates without time in C#.
In this example, we compare the two dates without time using the equality == operator, if both dates are the same then it will return true otherwise it will return false.
Here is the source code of the program to compare two dates without time using == Operator in C#.
using System;
namespace Tutorialsrack
{
class Program
{
/* How to compare two Dates without time in C# */
static void Main(string[] args)
{
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(-50);
if (date1.Date == date2.Date)
{
Console.WriteLine("Both the dates are same");
}
else
{
Console.WriteLine("Both the dates are not same");
}
//Hit ENTER to exit the program
Console.ReadKey();
}
}
}
In this example, we compare the value of this instance to a specified DateTime
value and indicate whether this instance is earlier than, the same as, or later than the specified DateTime
value.
A number indicating the relative values of this instance and the value parameter.
Compare Return Value:
Here is the source code of the program to compare the two dates without time using the .CompareTo() method in c#.
using System;
namespace Tutorialsrack
{
class Program
{
/* How to compare two Dates without time in C# */
static void Main(string[] args)
{
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(-50);
var compare = date1.Date.CompareTo(date2.Date);
switch (compare)
{
case 1:
Console.WriteLine("The Date1 is greater than the Date2.");
break;
case 0:
Console.WriteLine("The Date1 is the same as the Date2.");
break;
default:
Console.WriteLine("The Date1 is earlier date than the Date2.");
break;
}
//Hit ENTER to exit the program
Console.ReadKey();
}
}
}
I hope this article will help you to understand how to compare two dates without time in C#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments