Getmonth in JavaScript Gives Previous Month

getMonth in javascript gives previous month

Because getmonth() start from 0. You may want to have d1.getMonth() + 1 to achieve what you want.

Javascript getMonth returning previous month after adding days

Months from Data.getMonth are zero based (so January is 0, feb is 1, etc).

So if you want to use the month value to make a new date just add one.

How to reliably get previous month from js Date?

Just use clone.setDate(0) and you will get the last day of previous month

const dates = [new Date(2021,0,15), new Date(2021,2,31)]

const getPreviousMonth = date => {
const clone = new Date(date)
clone.setDate(0)
return clone
}

dates.forEach(d=>{
console.log(getPreviousMonth(d))
})

Why date().getMonth() return wrong month

The months in JavaScript are zero indexed, so January is 0 and December is 11. That makes October 9.

Strange behaviour of Date.getMonth() - Month difference

Javascript dates start at 0 for months

example:

  • 0: Jan
  • 1: Feb
  • 2: Mar
  • etc

Why is Month Returning Last Month?

Javascript month begins at 0 not 1

Javascript - Get Previous Months Date

var myVariable = "28 Aug 2014"
var makeDate = new Date(myVariable);
makeDate = new Date(makeDate.setMonth(makeDate.getMonth() - 1));

Update:

A shorter version:

var myVariable = "28 Aug 2014"var makeDate = new Date(myVariable);
console.log('Original date: ', makeDate.toString());
makeDate.setMonth(makeDate.getMonth() - 1);
console.log('After subtracting a month: ', makeDate.toString());


Related Topics



Leave a reply



Submit