简体   繁体   中英

JavaScript creating a Date Object x seconds Ago?

Say I have a number x that can be anything (within reason). How would I create a new Date object that is x number of seconds ago? 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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