javascript 如何在javascript中获得减去20秒的当前日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20874281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:31:02  来源:igfitidea点击:

how can I get the current date minus 20 seconds in javascript?

javascripthtmldateget

提问by user3147580

how can I get the current date minus 20 seconds in javascript? I can not figure out how to subtract 20 seconds to the current date in javascript how can I do, I get a negative value in this way

如何在javascript中获得减去20秒的当前日期?我不知道如何在 javascript 中将当前日期减去 20 秒我该怎么做,我以这种方式得到一个负值

There is an easier way? thanks

有更简单的方法吗?谢谢

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

回答by cookie monster

Give this a shot:

试一试:

new Date(Date.now() - 20000);

The Date.now()returns the milliseconds since Jan 1, 1970 00:00:00, so we just subtract 20000 milliseconds from that, and use the result to create a new date.

Date.now()自1970年1月1日00:00:00返回毫秒,所以我们只是减去从20000毫秒,并使用结果来创建一个新的日期。

As @rjz noted, you'll need a shim for old IE. The MDN shim is below:

正如@rjz 所指出的,旧的 IE 需要一个垫片。MDN 垫片如下:

if (!Date.now) {
     Date.now = function() { return new Date().getTime(); }
}

回答by Matt Johnson-Pint

Using moment.js:

使用moment.js

moment().subtract(20, 'seconds')

Or if you actually need a Dateobject:

或者,如果您确实需要一个Date对象:

moment().subtract(20, 'seconds').toDate()

回答by Michael Geary

I would do it something like this:

我会这样做:

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()
);

With this code you don't need any shims or polyfills or any of that stuff. I just tested it in IE 5.5 and Netscape 4.79 and it works fine there! That's why I used alert()in the test instead of console.log(), so I could test it in those old browsers.

使用此代码,您不需要任何垫片或 polyfill 或任何此类东西。我刚刚在 IE 5.5 和 Netscape 4.79 中测试了它,它在那里运行良好!这就是为什么我alert()在测试中使用而不是console.log(),所以我可以在那些旧浏览器中测试它。

回答by CRABOLO

Remove the - 20 that appears after getSeconds()

删除 getSeconds() 之后出现的 - 20

and then add this a line below it or more

然后在它下面添加一行或更多

secondi = secondi - 20;