如何向 JavaScript 日期对象添加 10 秒?
像这样的东西:
var timeObject = new Date()
var seconds = timeObject.getSeconds() + 10;
timeObject = timeObject + seconds;
如何向 JavaScript 日期对象添加 10 秒?
像这样的东西:
var timeObject = new Date()
var seconds = timeObject.getSeconds() + 10;
timeObject = timeObject + seconds;
还有一个setSeconds
方法:
var t = new Date();
t.setSeconds(t.getSeconds() + 10);
有关其他 Date
功能的列表,您应该查看 MDN
setSeconds
将正确处理环绕情况:
var d;
d = new Date('2014-01-01 10:11:55');
alert(d.getMinutes() + ':' + d.getSeconds()); //11:55
d.setSeconds(d.getSeconds() + 10);
alert(d.getMinutes() + ':0' + d.getSeconds()); //12:05
// let timeObject = new Date();
// let milliseconds= 10 * 1000; // 10 seconds = 10000 milliseconds
timeObject = new Date(timeObject.getTime() + milliseconds);
只是为了我们中间的表演狂。
var d = new Date('2014-01-01 10:11:55');
d = new Date(d.getTime() + 10000);
5,196,949 次操作/秒,最快
var d = new Date('2014-01-01 10:11:55');
d.setSeconds(d.getSeconds() + 10);
2,936,604 次操作/秒,慢 43%
var d = new moment('2014-01-01 10:11:55');
d = d.add(10, 'seconds');
22,549 次操作/秒,慢 100%
所以也许它是人类最不可读的(不是那么糟糕),但它是最快的方式:)
const timeObject = new Date();
timeObject = new Date(timeObject.getTime() + 1000 * 10);
console.log(timeObject);
试试这个
a = new Date();
a.setSeconds(a.getSeconds() + 10);