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.

6
  • 2
    You'll need to have your datetime as a Date object Commented Jul 26, 2018 at 8:40
  • 2
    Consider momentjs.com library for date manipulations. Commented Jul 26, 2018 at 8:41
  • 2
    Also, "It didn't work" is really not enough information - please share what exactly happened - did you get any errors? Commented Jul 26, 2018 at 8:41
  • Your datetime is a String. Setting hours on a String doesn't make any sense - as Lix suggests, datetime needs to be a Date. Commented Jul 26, 2018 at 8:43
  • 3
    new Date("2018-07-25 20:23:22") Commented Jul 26, 2018 at 8:44

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

Comments

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());

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.