C#'s AddMonths
alters the month of the DateTime
much the sames as JavaScript's setMonth
does. However, importantly, AddMonths
takes into account edges cases like needing to go forward/backward a year or what happens when the particular date is not valid for that month. For example, if you subtract a month from March 29th, 2017 there was no February 29th that year. As a result, the date component also needs to change to 28. If it's a leap year, there will be, though, so you have to take that into account as well.
JavaScript's setMonth
is relatively dumb by comparison. It literally just modifies the month and then lets the date overflow as needed. For example, with the previous scenario of subtracting a month from March 29th, 2017 JavaScript will actually give you March 1, 2017, as it went to February 1, and then added the date component of 29 days. Since February only has 28, it wraps back around to March. It is at least smart enough to take leap years into account, so in a year like 2016, you would actually end up with February 29th.
Regardless, JavaScript dates pretty much suck. If you truly want to work with them, I'd suggest using a library like Moment.js, which among other things, smartly handles these types of situations.
Your best solution, though, might be to simply persist the default value from C#, so you don't have to worry about having to calculate it later via JavaScript. For example, you could add a data-*
attribute like:
.HtmlAttributes(new { data_default = DateTime.Now.AddMonths(-1) })
Then, you can simply read this value from the input and set the control to that when it's cleared.