Working with .NET’s DateTime
class can be a pain in the butt. Calculating dates in the future isn’t difficult, but it can take a bit of work to get to the right solution. If you’re reading this, well, you’re in luck!
We’re about to see how to solve for the next occurrence of a particular day (Monday, Tuesday, Wednesday, etc.) given an initial starting date. The solution is in C#, but we could apply the same code to any other programming languages.
Solving For The Next Day With C#
When working with .NET, we often deal with the DateTime
class. This class encapsulates multiple data points in on consumable type. Some data points include the date, time, day of the week, ticks, and much more. The two critical pieces of information we need to solve our particular problem are Date
and DayOfWeek
. The DayOfWeek
is an enumeration with an unsurprising set of values.
Great, so let’s design our surface API given we know what problem we’re solving.
Given a starting date, we would like the date(s)
of the next day of the week(s) that we provide.
In our case, our method signature might look something like this.
Note that we’ll use extension methods to invoke our method right off a DateTime
instance. Let’s look at a single usage.
In addition to getting a single value, I wanted the ability to get multiple calculations back at a time.
This implementation will calculate the dates for each distinct DayOfWeek
value passed into the method. What about calculating dates based on the previous result?
Here is an additional overload that allows us to select the calculation kind, either using the default And
value or the AndThen
value. This overload will treat each new DayOfWeek
as expecting to be calculated from the previous result. Imagine looking at a column in your calendar app; it would be as if you were potentially moving from row to row.
So where’s the code?! Well, let’s start with the main calculation.
- We first skip the current date as it may be the same
DayOfWeek
we’re currently seeking to calculate. - We want to calculate the number of days from our current date to get to the next day of the week. We use the
%
operator to constrain the result between0
and7
. - Finally, we add those days to the original date + 1 day (skipping the original date).
Once we have the heart of the calculation sorted out, we can build our additional variants.
These two additional methods allow us to pass in more than one day of the week at a time and calculate multiple dates. Here are all the scenarios in use.
And here is the complete implementation.
I hope you found this post useful, and please let me know in the comments if you have other calculations that you’re using for your applications.