user2925795
user2925795

Reputation: 398

How to manipulate date in JavaScript

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
}

Upvotes: 1

Views: 1661

Answers (4)

noggin182
noggin182

Reputation: 637

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
}

Upvotes: 2

C14L
C14L

Reputation: 12558

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.

Upvotes: 5

guest271314
guest271314

Reputation: 1

Use .getTime()

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

Upvotes: 0

AlexanderGriffin
AlexanderGriffin

Reputation: 515

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

Upvotes: 0

Related Questions