Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add 24 hours to datetime object of javascript [duplicate]

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

like image 366
Mohammad Sadiq Shaikh Avatar asked Dec 07 '12 12:12

Mohammad Sadiq Shaikh


Video Answer


2 Answers

One possible solution:

new Date(new Date(myStringDate).getTime() + 60 * 60 * 24 * 1000);
like image 186
VisioN Avatar answered Oct 16 '22 02:10

VisioN


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

like image 36
Moritz Roessler Avatar answered Oct 16 '22 03:10

Moritz Roessler