如何在javascript中获取当前日期减去20秒? 我无法弄清楚如何在javascript中减去20秒到当前日期 我该怎么做,我以这种方式获得负值
有一种更简单的方法吗? 感谢
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var ora = currentDate.getHours()
var minuti = currentDate.getMinutes()
var secondi = currentDate.getSeconds()-20
答案 0 :(得分:16)
试一试:
new Date(Date.now() - 20000);
Date.now()
返回自1970年1月1日00:00:00以来的毫秒数,因此我们只需从中减去20000毫秒,并使用结果创建新日期。
正如@rjz所说,你需要一个旧的IE垫片。 MDN垫片如下:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
答案 1 :(得分:1)
我会这样做:
function DateOffset( offset ) {
return new Date( +new Date + offset );
}
var twentySecondsAgo = DateOffset( -20000 );
// Should differ by 20 seconds (modulo 60)
alert(
twentySecondsAgo.getSeconds() +
'\n' +
new Date().getSeconds()
);
使用此代码,您不需要任何垫片或polyfill或任何东西。我刚刚在IE 5.5和Netscape 4.79中测试过,它在那里工作得很好!这就是我在测试中使用alert()
而不是console.log()
的原因,因此我可以在旧版浏览器中对其进行测试。
答案 2 :(得分:1)
使用moment.js:
moment().subtract(20, 'seconds')
或者如果您确实需要Date
对象:
moment().subtract(20, 'seconds').toDate()
答案 3 :(得分:0)
删除在getSeconds()
之后出现的 - 20然后在它下面添加一行或更多
secondi = secondi - 20;