简体   繁体   English

JavaScript创建日期对象x秒前?

[英]JavaScript creating a Date Object x seconds Ago?

Say I have a number x that can be anything (within reason). 假设我有一个数字x可以是任何东西(在合理范围内)。 How would I create a new Date object that is x number of seconds ago? 如何创建x个秒前的新Date对象? I have no idea about how to approach this. 我不知道如何处理这个问题。

var seconds = 5;
var dateNow = new Date();
var date5SecondsAgo = new Date(dateNow.getTime() - seconds*1000);
var now = new Date();
var seconds = 15;
var before = new Date(now.getTime() - seconds*1000);

You can use the valueOf/getTime property to get the the number of milliseconds since Jan 1, 1970 and then there are 1,000 milliseconds in a seconds 您可以使用valueOf / getTime属性来获取自1970年1月1日以来的毫秒数,然后在几秒钟内有1,000毫秒

var milliSecondPerSecond = 1000;
var myStartDate = new Date(myEndDateTime - numberOfSeconds * milliSecondPerSecond );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM