Javascript Relative Time 24 Hours Ago Etc as Time [Duplicate]

I am trying to use highcharts to show some data over the last 24 hours. The chart requires the start time when you use the time for the x axis like in this example Highcharts time example. I can't 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 believe 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.

0

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)

0

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:

Edit: As Nick correctly pointed out, Date#getTime returns the UTC timestamp ()

2

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'

Just subtract the amount of milliseconds in 24 hours from the date:

new Date (Date.UTC(2012, 5, 17, 22, 34) - 24 * 3600 * 1000)
2
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest