I am using a datepicker which gives a date in the format Sun Jul 7 00:00:00 EDT 2013.
Even though the month says July, if I do a getMonth, it gives me the previous month.
var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
d1.getMonth());//gives 6 instead of 7
What am I doing wrong?
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!
Presuming you use your variable
var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
Month requires a +1 to be accurate, it starts counting at 0
d1.getMonth() + 1 // month
In contrast.... these methods DON'T need a plus 1
d1.getSeconds() // seconds
d1.getMinutes() // minutes
d1.getDate() // date
And notice it is .getDate()
NOT .getDay()
d1.getDay() // day of the week as a
Hope this helps
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
本文地址:http://javascript.askforanswer.com/getmonth-in-javascript-gives-previous-month.html
文章标签:date , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
文章标签:date , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!