It looks like Javascript setMonth method does not change month correctly if it was used for 31st.
var event = new Date('July 31, 2018 10:48:30');
console.log(event.getMonth());
// output: 6
// Change to previous month
event.setMonth(event.getMonth() - 1);
console.log(event.getMonth());
// expected output: 5 actual output: 6
console.log(event);
Does anyone have a better option available to change month and set date of 30th if 31st is not in the month?
let previous = event.getMonth();
while(event.getMonth() === previous)
event.setDate(event.getDate() - 1);
Just go back day by day.
Does anyone have a better option available to change month and set date of 30th if 31st is not in the month?
Just go a day before:
var event = new Date('July 31, 2018 10:48:30');
console.log(event.getMonth());
// Change to previous month
var current = event.getMonth();
event.setMonth(current - 1);
if (event.getMonth() === current) {
event.setDate(event.getDate() - 1);
}
console.log(event.getMonth());
// actual output: 5
console.log(event);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.