Javascript relative time 24 hours ago etc as time

Totoro picture Totoro · Jun 17, 2012 · Viewed 40.3k times · Source

I am trying to use highcharts to show some data over the last 24 hours. The chart requires the start time when you use time for the x axis like in this example Highcharts time example. I cant figure out how to tell it to start 24 hours ago for example, if the time now was 22:34pm on the 18th, I want it to start at 22:34pm on the 17th. I am not very good with time and date related code and Javascript is also not my strong point. I belive I would need the finished output to be something like: pointStart: Date.UTC(2012, 5, 17, 22, 34) For the above example, but I'm not so sure how to get that from Date().

Edit: I am not sure why it was marked as a duplicate but I was trying to get a time relative to the current time (now - 24h), not a relative string representation (“twenty four hours ago”). The other question also does not mention highcharts at all.

Answer

Naftuli Kay picture Naftuli Kay · Dec 31, 2013

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)