1

I'm having problem with manipulation of dates. I have a variable savedTime variable in localstorage which contains this date:

Wed Aug 31 2016 16:31:30 GMT-0300 (Hora oficial do Brasil)

I need add 1 hour for this variable savedTime to check if passed 1 hour:

var savedTime = new Date(savedTime); //converts string to date object
var checkExpired = savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to savedTime

But on trying add 1 hour to this variable converting the string in a object, this (savedTime) returns:

1472675490000

What I expected is the string with + 1 hour:

Wed Aug 31 2016 17:31:30 GMT-0300 (Hora oficial do Brasil)

And compare dates to check if passed 1 hour

var currentDate = new Date();
if(currentDate > checkExpired) {
    //passed 1 hour
}
6
  • Do you want to be able to compare the dates or be able to format the number you got from the date? Commented Aug 31, 2016 at 20:59
  • Not certain what issue is? Commented Aug 31, 2016 at 21:00
  • You seem to be getting exactly what you want, but dates in javascript are in milliseconds, only the string representation is in the expected format ? Commented Aug 31, 2016 at 21:01
  • You are comparing 1472675490000 with 26 Wed Aug 31 2016 22:01:11 GMT+0100 (BST) which cant be compared to be greater than Commented Aug 31, 2016 at 21:01
  • I updated the question to explain better Commented Aug 31, 2016 at 21:04

4 Answers 4

5

instance.setHours() manipulates the instance. So you can do

d = new Date('Wed Aug 31 2016 16:31:30 GMT-0300');
d.setHours(d.getHours() + 1);

Now d contains the new datetime.

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

Comments

2

setHours will manipulate the current object and return it's new value. Instead of using the return value, just continue to use the object.

var savedTime = new Date(savedTime); //converts string to date object
savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to the savedTime

if (currentDate > savedTime) {
    //passed 1 hour
}

Comments

0

Use .getTime()

if(currentDate.getTime() > checkExpired) {
    //passed 1 hour
}

Comments

0

You are getting the value back in milliseconds from the 'epoch date' which is January first 1970.

If you want this in the correct format, you will need to parse this information out into that with some math / other Date object functions.

Here is the documentation to do that, it's very straightforward:

JS Date Formatting

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.