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();
2
  • check this Commented Feb 19, 2018 at 7: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'); Commented Feb 19, 2018 at 7:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.