Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript向后日期_Javascript_Date - Fatal编程技术网

Javascript向后日期

Javascript向后日期,javascript,date,Javascript,Date,我正在尝试计算使用前一天的日期: var da = new Date('2016-11-25'); nda = new Date(da-86400000); 当使用以下方式打印时,它似乎运行良好: document.write(nda); 输出为: 2016年11月24日星期四00:00:00 GMT+0000(湿) 这是正确的,但如果我这样做: document.write(nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay()); 我

我正在尝试计算使用前一天的日期:

var da = new Date('2016-11-25');
nda = new Date(da-86400000);
当使用以下方式打印时,它似乎运行良好:

document.write(nda);
输出为:

2016年11月24日星期四00:00:00 GMT+0000(湿)

这是正确的,但如果我这样做:

document.write(nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay());
我得到了一个错误的输出:

2016-10-4


有什么建议吗?

您需要执行
nda.getMonth()+1
。 月份从0开始,因此为了获得正确的月份数,必须添加1

您还需要使用
getDate()
而不是
getDay()
。getDay将为您提供一周中的某一天,而getDate将为您提供一个月中的某一天

最终结果将是:

nda.getFullYear() + "-" + (nda.getMonth() + 1) + "-" + nda.getDate()
var da=新日期('2016-11-25');
nda=新日期(da-86400000);
document.write((nda.getFullYear())+
“-”+(nda.getMonth()+1)+
“-”+(nda.getDate())返回该月的索引,索引为0(因此0是一月,11是十二月)。要对此进行更正,请添加1

返回一周中的某一天,该天也从星期日开始为0索引(因此4是星期四)

在这里,您将使用获取当前月份中的日期(该日期不是0索引的)

var da=新日期('2016-11-25'),
nda=新日期(da-86400000);
document.write(nda.getFullYear()+“-”+
(nda.getMonth()+1)+“-”+

nda.getDate())解析日期有一个基本规则:不要使用日期构造函数或Date.parse(它们在解析中是等效的)来解析日期字符串。将库与解析器一起使用,或者自己用简单的函数进行解析

使用时:

var da = new Date('2016-11-25');
该日期将被视为UTC,因此,如果您位于格林威治以西的时区,则本地日期将为前一天。请注意以下方面的差异:

console.log('内置解析:'+新日期('2016-11-25')。toLocaleString());

log('No parse:'+新日期(2016,10,25).toLocaleString())是否有任何不使用的原因:
var d=new Date();d、 setDate(d.getDate()-1)
getMonth()
返回一个介于0和11之间的数字,即1月0日,因此+1 ;)
getMonth()
根据本地时间返回指定日期中的月份,作为基于零的值(其中零表示一年中的第一个月),并且
getDay()
根据本地时间返回指定日期的星期几,其中0表示星期日-请参阅和@ScottMarcus上的MDN文档,原因是。。。它给出了相同的结果problem@FrançoisWahl谢谢!这解决了问题的一半,另一半是使用
getDay()