var fromDate = new Date();
var toDate = new Date();
fromDate.setDate(fromDate.getDate() - 1);
toDate.setDate(fromDate.getDate() - 30);
现在,当我打印 formDate 时,正在打印 Date 2018-07-31T05:33:46.399Z
现在打印 toDate 时,打印日期 2018-08-01T05:33:46.399Z
当前日期是日期 2018-08-01T06:00:46.921Z
所以我想获得昨天的日期和昨天的日期前 30 天如何在不使用时刻的情况下获得以前的日期
在setDate()
相对设置日期。第一个片段在您将日期设置为 时起作用0
,这会将上个月的最后一个日期设置为日期对象。根据文档
如果 dayValue 超出该月的日期值范围,
setDate()
将相应地更新 Date 对象。例如,如果为 提供 0dayValue
,则日期将设置为上个月的最后一天。
但是在第二个代码段中,您将日期设置为1
(31 - 30),这不会相对设置日期,但绝对设置,因为 1 是有效日期,并且不在范围之外。所以,你最终设定日期1
在toDate
。
正确的方法是从 中减去 31(假设您想要 7 月 1 日)toDate
,这会创建一个相对值 (1 - 31 == -30),从而正确设置日期。
var formDate = new Date();
var toDate = new Date();
formDate.setDate(formDate.getDate() - 1);
toDate.setDate(toDate.getDate() - 31);
console.log(formDate, toDate);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句