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
Detect Programmatic Changes on Input Type Text
Position Fixed Not Working in Mobile Browser
How to Select All Text in Contenteditable Div
Get the Dom Path of the Clicked <A>
Target='_Blank' to Show in New Window, Not New Tab, Possible
Open a New JavaScript Window(.Open) Along with Its CSS Styling
Es6 Module Import Giving "Uncaught Syntaxerror: Unexpected Identifier"
How to Limit Options Selected in a HTML Select Box
How to Disable Copy Paste (Browser)
Js: Get Array of All Selected Nodes in Contenteditable Div
Safari: Absolutely Positioned Divs Not Moving When Updated via Dom
Js & Jquery Can't Detect HTML Elements, and Say's They Are Undefined
How to Convert a Float Number to a Whole Number in JavaScript
Declaring JavaScript Object Method in Constructor Function VS. in Prototype
How to Display All Methods of an Object
Chrome Extension Code VS Content Scripts VS Injected Scripts