4

I want to add hours in DateTime. I have googled it but couldn't find any code.

Here is this datetime 2018-07-25 20:23:22. I want to add hours in this datetime so it gives me new datetime in the same format

I have tried this.

var datetime = "2018-07-25 20:23:22";
datetime.setHours(datetime.getHours()+5); 

But It didn't work.

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
user1hjgjhgjhggjhg
  • 1,237
  • 4
  • 15
  • 34

2 Answers2

17

Your datetime is String. You need to convert it into Date object first.

var datetime = new Date("2018-07-25 20:23:22");
console.log("Before: ", datetime);
datetime.setHours(datetime.getHours()+1); 
console.log("After: ", datetime);

I would prefer to use moment.js library for manipulating and playing with dates.

Hope this may help you.

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
6

Here is the simple way with using Moment.js

const date = moment('2018-07-25 20:23:22');
date.add(5, 'h');
console.log(date.toString());
YuraGon
  • 147
  • 6