25

Possible Duplicate:
Adding hours to Javascript Date object?

I am having javascript datetime object .

I want to add 24 hours to that datetime

for ex.

if it is 2 dec 2012 3:30:00 => 3 dec 2012 3:29:00

if it is 31 dec 2012 3:30:00 => 1 jan 2013 3:29:00

etc

any suggestion ????

2
  • I haven't tried following code. But please believe in searching (a) stackoverflow.com/questions/1050720/… Commented Dec 7, 2012 at 12:18
  • 2
    Doesn't theDate.setDate(theDate.getDate()+1); work? Commented Dec 7, 2012 at 12:49

2 Answers 2

53

One possible solution:

new Date(new Date(myStringDate).getTime() + 60 * 60 * 24 * 1000);
Sign up to request clarification or add additional context in comments.

6 Comments

Why not just var a = new Date(); a.setDate(a.getDate()+1); ?
@Ian This is almost the same as Glutamat posted. Mine is yet another possible solution.
Oh of course they're both definitely solutions, I'm just wondering why a solution based on days wasn't proposed since that's what it's about. They all definitely work, I just thought the .setDate made since for moving by day.
Of course, there are many possible solutions,i like adjusting ms kind of more, so +1 on this but since the OP asked for adding (24) Hours, i just thought, why not giving him a solution where hours are used,
@ÆtherSurfer That makes no sense. It doesn't do that at all. It works exactly as expected. jsfiddle.net/T4Y49
|
44

This would be one way

var myDate = new Date("2 dec 2012 3:30:00") // your date object
myDate.setHours(myDate.getHours() + 24)
console.log(myDate) //Mon Dec 03 2012 03:30:00 GMT+0100 (Mitteleuropäische Zeit)
  • Date.setHours allows you to set the Hours of your Date Object
  • Date.getHours retrieves them

In this Solution it simply gets the Hours from your Date Object adds 24 and writes them Back to your object.

Of course there are other Possible ways of achieving the same result e.g.

  • Adjusting the milliseconds

    • Date.getTime gives you the milliseconds of the Object since midnight Jan 1, 1970
    • Date.setTime sets them

So adding 24 * 60 * 60 * 1000 or 86400000 milliseconds to your Date Object will result in the same See VisioNs Answer

  • Adding a Day
    • Date.getDate gets the Date of the month of your Date Object
    • Date.setDate sets them

Increasing it by one, will again result in the same
As Ian mentioned in a comment

So its just depends on what feels the most understandable for you And if you want to, give this w3schools examples a look, to get a starting point of dealing with Dates

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.