2

Trying to get the current time and the current time - 3 hours in javascript in the UTC, per ISO 8601 format.

pastTime is not working. Getting an error as 'pastTime.setHours(...).toISOString is not a function'

This is the code:

let currentTime = new Date().toISOString();
let pastTime = new Date();
pastTime = pastTime.setHours(new Date().getHours()-3).toISOString();
Cœur
  • 37,241
  • 25
  • 195
  • 267
MSD
  • 1,409
  • 12
  • 25
  • [check this](https://stackoverflow.com/questions/9756120/how-do-i-get-a-utc-timestamp-in-javascript) – NnN Feb 19 '18 at 07:49
  • 2
    Use momentjs in your project for better and easier date manipulation, in momentjs you can achieve it by `moment(realTime, 'HH:mm').subtract(3, 'hours');` – sidgujrathi Feb 19 '18 at 07:56

1 Answers1

2

I edited your code here:

var pastTime = new Date();
pastTime.setHours(new Date().getHours()-3);
pastTime = pastTime.toISOString();

You can't set hours and get an ISO string in one step, if you were to save what the setHours() function returns, it is in the wrong format to be accepted by the toISOString() function. It returns it in milliseconds since January 1, 1970 00:00:00 UTC until the time you're retrieving.

That is why when you tried saving it to pastTime, that would put it in the wrong format (milliseconds), you need to just change the value without saving it to pastTime, and then save a new version of pastTime with ISO format.

Levi Blodgett
  • 354
  • 1
  • 3
  • 16