Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DateTime of the next nth day of the month

Tags:

c#

datetime

If given a date and a variable n, how can I calculate the DateTime for which the day of the month will be the nth Date?

For example, Today is the 17th of June. I would like a function that when provided 15 would return the DateTime for July 15.

A few more examples:

  • Today is Feb. 26: Function would return March 30 when provided 30.
  • Today is Dec. 28. Function would return Jan 4 when provided 4.
  • Today is Feb. 28. Function would return March 29 when provided 29, unless it was a leap year, in which case it would return Feb 29.
like image 717
S. Walker Avatar asked Nov 15 '25 22:11

S. Walker


1 Answers

Why not just do?

private DateTime GetNextDate(DateTime dt, int DesiredDay)
{
    if (DesiredDay >= 1 && DesiredDay <= 31)
    {
        do
        {
            dt = dt.AddDays(1);
        } while (dt.Day != DesiredDay);
        return dt.Date;
    }
    else
    {
        throw new ArgumentOutOfRangeException();
    }     
}
like image 51
Idle_Mind Avatar answered Nov 17 '25 11:11

Idle_Mind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!