In our applications, there may be a need to check if an input date string is less than or equal to today’s date. This information is crucial for various scenarios, including scheduling events, validating user-entered dates, and updating entities in our database.
In this article, we will explore various methods that we can use to check if a date is less than or equal to today’s date. We will start by preparing our DateOnly object. Then, we will proceed to discuss the various methods. To conclude the article, we’ll perform a benchmark test to determine the fastest method for obtaining this information.
So, let’s start.
Setup the Environment
Let’s start by defining the current day’s date and our input date:
public class DateComparer { private readonly DateOnly _todayDate; private readonly DateOnly _dateToCheck; public DateComparer(string dateString = "01/01/2024") { _todayDate = DateOnly.FromDateTime(DateTime.Today); if (!DateOnly.TryParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _dateToCheck)) { // Handle a case where the input date string is invalid } } }
First, we create a DateComparer
class. Then, we define two readonly
DateOnly fields called _todayDate
and _dateToCheck
. We create DateOnly
fields so that we can concentrate solely on the dates and eliminate concerns about time and time zone differences.
In our constructor, we add the input date string as an optional parameter with a default value of 01/01/2024
. Then, we obtain the present day’s date by calling the FromDateTime()
method with DateTime.Today
as an argument.
After that, we convert our input date string to a DateOnly
object. We do this by calling the TryParseExact()
method, specifying that our DateOnly
instance should be in the MM/dd/yyyy
format. We also specify that it should be culture-independent, have no style, and that the output of our conversion should be stored in the _dateToCheck
variable.
Finally, if the parsing fails, we handle a scenario where the input date string is invalid.
Ways to Check if a Date Is Less Than or Equal to Today’s Date
Now that our dates are ready, let’s examine four methods that we can utilize to calculate if a date is less than or equal to today’s date.
Check With the Less Than or Equal to Operator (<=)
First, let’s use the <=
(less than or equal to) comparison operator:
public bool CheckWithComparisonOperator() => _dateToCheck <= _todayDate;
This is an expression-bodied method that returns true if our date is earlier than or equal to the present day’s date, and false otherwise.
Use the CompareTo Method
Next, let’s use the built-in CompareTo()
method:
public bool CheckWithCompareTo() => _dateToCheck.CompareTo(_todayDate) <= 0;
Here, we invoke the CompareTo()
method on _dateToCheck
, and we pass in _todayDate
as an argument. The CompareTo()
method returns a positive integer if the date is greater than today, a negative integer if the date is less than today, and 0 if the two dates are equal.
If the comparison result is less than or equal to 0, the method returns true, indicating that _dateToCheck
is either less than or equal to today’s date. Otherwise, it returns false, signifying that _dateToCheck
is greater than today’s date.
Check With the DayNumber Property
Now, let’s introduce another approach using the DayNumber
property:
public bool CheckWithDayNumber() => _dateToCheck.DayNumber <= _todayDate.DayNumber;
The DayNumber
property of a DateOnly
instance represents the number of days since January 01, 0001, in the Proleptic Gregorian Calendar.
In this method, we simply check if the DayNumber
property of _dateToCheck
is less than or equal to that of _todayDate
. If it is, the method returns true signifying that _dateToCheck
is either less than or equal to today’s date. Otherwise, it returns false, indicating that _dateToCheck
is later than today.
Check Using a TimeSpan
Moving on, let’s utilize the TimeSpan struct. Since this struct requires a time component, let’s add and initialize two DateTime fields in our DateComparer
class:
public class DateComparer { private readonly DateOnly _todayDate; private readonly DateOnly _dateToCheck; private readonly DateTime _todayDateTime; private readonly DateTime _dateTimeToCheck; public DateComparer(string dateString = "01/01/2024") { _todayDate = DateOnly.FromDateTime(DateTime.Today); if (!DateOnly.TryParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _dateToCheck)) { // Handle a case where the input date string is invalid } _todayDateTime = _todayDate.ToDateTime(TimeOnly.MinValue); _dateTimeToCheck = _dateToCheck.ToDateTime(TimeOnly.MinValue); } }
Here, we define two DateTime
fields, _todayDateTime
and _dateTimeToCheck
.
Then, in our constructor, we initialize them by invoking the ToDateTime()
method on our DateOnly
objects. We pass in the TimeOnly.MinValue
property, representing 00:00:00
(midnight), to this method. This allows us to effectively compare only the dates and not be concerned about the time.
With that, let’s create our CheckWithTimeSpan()
method:
public bool CheckWithTimeSpan() { TimeSpan timeDifference = _dateTimeToCheck - _todayDateTime; return timeDifference.TotalDays <= 0; }
First, we define a TimeSpan
variable to store the time interval between our input date and the present day’s date.
Subsequently, we measure the total duration of this interval in days and check if it is less than or equal to 0. If it is, it shows that our input date is either earlier than or equal to today’s date.
Benchmark Methods To Check if a Date Is Less Than or Equal to Today
Now, with all our methods ready, let’s use the BenchmarkDotNet
library to compare their performance. To learn more about benchmarking, be sure to check out our article: Introduction to Benchmarking C# Projects.
We should note that BenchmarkDotNet
automatically determines the number of times to invoke our methods during each benchmark by default. The library does this to ensure that our results are reliable.
Let’s create our benchmark class:
[Orderer(SummaryOrderPolicy.FastestToSlowest)] public class DateComparerBenchmark { private readonly DateComparer _dateComparer; public DateComparerBenchmark() { _dateComparer = new DateComparer(DateTime.Today.ToString("MM/dd/yyyy")); } [Benchmark] public bool CheckWithComparisonOperator() => _dateComparer.CheckWithComparisonOperator(); [Benchmark] public bool CheckWithCompareTo() => _dateComparer.CheckWithCompareTo(); [Benchmark] public bool CheckWithDayNumber() => _dateComparer.CheckWithDayNumber(); [Benchmark] public bool CheckWithTimeSpan() => _dateComparer.CheckWithTimeSpan(); }
Next, let’s check our results:
| Method | Mean | Error | StdDev | |---------------------------- |----------:|----------:|----------:| | CheckWithComparisonOperator | 0.4418 ns | 0.0151 ns | 0.0134 ns | | CheckWithDayNumber | 0.5430 ns | 0.0033 ns | 0.0030 ns | | CheckWithCompareTo | 0.6509 ns | 0.0291 ns | 0.0227 ns | | CheckWithTimeSpan | 0.8446 ns | 0.0013 ns | 0.0012 ns |
As we can see from these results, using the less than or equal to comparison operator (<=) is the fastest way to check if a date is less than or equal to today’s date. After that, we have the CheckWithDayNumber()
method as the second fastest followed by the CheckWithCompareTo()
methods.
Finally, the slowest way to perform this task is by using the Timespan
struct.
Conclusion
In this article, we discussed various ways to check if a date is less than or equal to today’s date in C#.
We started by creating our input DateOnly object. Then, we defined various methods for performing this comparison.
In the end, we ran our benchmark tests and discovered that the fastest way to check if a date is less than or equal to today’s date is by using the less than or equal to comparison operator (<=).