Reputation: 8707
I have a below JS where I get the max date that is user allowed to enter from a backend script:
var max_date = new Date(pdate + " " + ptime);
where pdate and ptime is fetched from a script.
Now I need to set the min date as 1 month less than max_date
if (max_date.getMonth() == 0)
subtractyear = 1;
var min_date = new Date(Date.UTC(max_date.getFullYear() - subtractyear,max_date.getMonth() - 1,max_date.getDate(),max_date.getHours(),0,0));
My issue is that if max_date is March 31 - then will the min_date be rolled over to Feb 28 or Feb 29 or Feb 31 or Feb 30?
If the date formed is an incorrect date - say Feb 30 how can I rectify this?
Upvotes: 2
Views: 20508
Reputation: 12395
Simple subject the month by 1 would get a valid date -- never would setMonth
method return an invalid Date
object (the same as setDate
, setYear
and the Date
constructor):
var date = new Date(2012, 02, 31); // 2012-03-31
date.setMonth(date.getMonth() - 1); // This gets 2012-03-02
I don't quite clear what date you expected, the last day of the previous month or just the day one month earlier?
Upvotes: 7