Add time to string data/time - JavaScript?


At first, set a new Date in JavaScript −

var dateValue = new Date("2021-01-12 10:10:20");

Use new Date() along with setHours() and getHours() to add time.

Example

Following is the code −

var dateValue = new Date("2021-01-12 10:10:20");
dateValue.setHours(dateValue.getHours() + 2);
console.log("The date value is=" + dateValue.toString());
console.log("Only Hours value after incrementing=" +
dateValue.getHours());

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo291.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo291.js
The date value is=Tue Jan 12 2021 12:10:20 GMT+0530 (India Standard Time)
Only Hours value after incrementing=12

Updated on: 09-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements