-2

I have time which is dynamic in 12 hour format.

Now i want to add 1 hour to the time.

I am adding 1 hour like

s_time = parseFloat(s_time) + 1;

But i dont think it is proper way to do it.

So can you guys suggest me how to do it.

Thanks

sanjay rathod
  • 77
  • 1
  • 2
  • 16
  • 3
    Post a [mcve] please. And since JavaScript typically works in seconds, you may just need to add 3600 to what you have, but without a complete example it's difficult to say. – j08691 Jan 09 '17 at 14:19
  • The proper way would be to actually use JavaScript Dates, not just numbers. But I guess you could use the `%` operator to get the 12 hour format. Example : `(5 + 1) % 12 = 6`, `(12 + 1) % 12 = 1`, ... – blex Jan 09 '17 at 14:21
  • Yes but he is considering 24 hour time period – sanjay rathod Jan 09 '17 at 14:21

2 Answers2

6
var oldDate = new Date();
var hour = oldDate.getHours();
var newDate = oldDate.setHours(hour + 1);
console.log(newDate);
sandrooco
  • 8,016
  • 9
  • 48
  • 86
1

If you are having a date object, define a function like this and call wherever you want.

var addHours= function(dateObj, numHours){
   var copiedDate = new Date(dateObj.getTime()); //cloning the date object.
   copiedDate.setHours(copiedDate .getHours()+numHours);
   return copiedDate;
}

Since the setDate() function will change the current object, we are cloning it.