This is because the getMonth method returns a zero-based number between 0 and 11 . For example, January is 0 , February is 1 , March is 2 , etc. If you need to get a one-based value for the month, simply add 1 to the result. Copied!
To get the first day of the previous month, use the Date() constructor to create a date object, passing it a call to the getFullYear() method for the year, a call to the getMonth() method - 1 to get the previous month and 1 for the day.
The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).
Because getmonth() start from 0. You may want to have d1.getMonth() + 1
to achieve what you want.
getMonth()
function is zero indexed based. You need to do d1.getMonth() + 1
Recently I used Moment.js library and never looked back. Try it!
var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
d1.getMonth() + 1 // month
d1.getSeconds() // seconds
d1.getMinutes() // minutes
d1.getDate() // date
.getDate()
NOT .getDay()
d1.getDay() // day of the week as a
I suspect these methods lack consistency for historical reasons
const d = new Date();
const time = d.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second:'numeric', hour12: true });
const date = d.toLocaleString('en-US', { day: 'numeric', month: 'numeric', year:'numeric' });
OR
const full_date = new Date().toLocaleDateString(); //Date String
const full_time = new Date().toLocaleTimeString(); // Time String
Output
Date = 8/13/2020
Time = 12:06:13 AM
Yes, this seems to have been a boneheaded decision on someone's part to make the month zero-indexed while the year and day are not. Here's a little function I use to convert a date into the format expected for the field...
const now = new Date()
const month = (date) => {
const m = date.getMonth() + 1;
if (m.toString().length === 1) {
return `0${m}`;
} else {
return m;
}
};
const day = (date) => {
const d = date.getDate();
if (d.toString().length === 1) {
return `0${d}`;
} else {
return d;
}
};
const formattedDate = `${now.getFullYear()}-${month(now)}-${day(now)}`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With