JS中的日期代码不起作用 [英] Date code not working in JS
本文介绍了JS中的日期代码不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
2015-01-01
之类的字符串构建的日期。 firstDate ='2015-01-01';
var t1_date = new Date(firstDate);
t1_date.setTime(t1_date.getTime()+ 90 * 86400000);
lastDate = getFormattedDate(t1_date);
console.log(Two dates:,firstDate,lastDate);
函数getFormattedDate(date){
var year = date.getFullYear();
var month = date.getMonth()。toString();
month = month.length> 1?月:'0'+月
var day = date.getDate()。toString();
day = day.length> 1?天:'0'+天;
返回年+' - '+月+' - '+天;
}
然后:
我得到的输出是错误的,因为我添加了90天..
两个日期:2015-01-01 2015 -02-31
解决方案
问题在于这一行:
var month = date.getMonth()。toString();
功能 Date.getMonth()返回指定日期根据本地时间的月份(0-11)。 1月是 0
,12月是 11
,所以你需要添加1到输出:
var month =+(date.getMonth()+ 1);
I bet this is something really silly but I am tired and looking for a quick escape so please indulge me. Objective is to be able to add arbitrary days to a date constructed from a string like 2015-01-01
.
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = date.getMonth().toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month + '-' + day;
}
And then :
I get the output which is wrong because I am adding 90 days..
Two dates: 2015-01-01 2015-02-31
解决方案
The problem lies in this line:
var month = date.getMonth().toString();
The function Date.getMonth() returns "the month (0-11) in the specified date according to local time". January is 0
, December is 11
, so you need to add 1 to the output:
var month = "" + (date.getMonth()+1);
这篇关于JS中的日期代码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文