Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 665
yourface Avatar asked Mar 14 '12 05:03

yourface


3 Answers

var seconds = 5;
var dateNow = new Date();
var date5SecondsAgo = new Date(dateNow.getTime() - seconds*1000);
like image 126
mVChr Avatar answered Nov 10 '22 08:11

mVChr


var now = new Date();
var seconds = 15;
var before = new Date(now.getTime() - seconds*1000);
like image 32
Yoann Avatar answered Nov 10 '22 09:11

Yoann


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 );
like image 1
Baz1nga Avatar answered Nov 10 '22 08:11

Baz1nga