23

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 ????

Community
  • 1
  • 1
Mohammad Sadiq Shaikh
  • 3,160
  • 9
  • 35
  • 54
  • I haven't tried following code. But please believe in searching (a) http://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object – t1w Dec 07 '12 at 12:18
  • 2
    Doesn't `theDate.setDate(theDate.getDate()+1);` work? – Ian Dec 07 '12 at 12:49

2 Answers2

49

One possible solution:

new Date(new Date(myStringDate).getTime() + 60 * 60 * 24 * 1000);
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 7
    Why not just `var a = new Date(); a.setDate(a.getDate()+1);` ? – Ian Dec 07 '12 at 12:47
  • @Ian This is almost the same as [Glutamat posted](http://stackoverflow.com/a/13762964/1249581). Mine is yet another possible solution. – VisioN Dec 07 '12 at 12:52
  • 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. – Ian Dec 07 '12 at 12:54
  • 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, – Moritz Roessler Dec 07 '12 at 13:22
  • @ÆtherSurfer That makes no sense. It doesn't do that at all. It works exactly as expected. http://jsfiddle.net/T4Y49/ – Ian Oct 23 '13 at 23:25
  • @Ian I see now. I will delete my comment then. – Gabriel Oct 24 '13 at 22:49
39

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

Community
  • 1
  • 1
Moritz Roessler
  • 8,542
  • 26
  • 51