Javascript relative time 24 hours ago etc as time

This is actually fairly simple:

var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));

Simply construct a new Date with the value of the current timestamp minus 24 hours.

(24 hours multiplied by 60 minutes in each hour multiplied by 60 seconds in each minute multiplied by 1000 milliseconds in each second)


24 hours ago:

new Date(Date.now() - 86400 * 1000).toISOString()

  1. now: new Date().toISOString()
  2. outputs: '2017-02-04T09:15:25.233Z'
  3. Date.now() returns seconds since epoch.
  4. Subtract 86400 seconds in a day times 1000 to convert to milliseconds
  5. outputs: '2017-02-03T09:14:11.789Z'

You should use timestamps as you can calculate with them.

This is how you get the current timestamp: Math.round(new Date().getTime() / 1000) Please note that this the computers local time.

Now you can get the timestamp 24 hours ago like this:

var ts = Math.round(new Date().getTime() / 1000);
var tsYesterday = ts - (24 * 3600);

Please see this fiddle: http://jsfiddle.net/Mjm7V/

Edit: As Nick correctly pointed out, Date#getTime returns the UTC timestamp (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime)