Before that, let’s see what is a date object.
What Is Date?
You can view the latest Mozilla Documentation Here.
How To Create An Instance Of Date?
These are some examples that show how you can create a date –
const today = new Date() const newYears = new Date('January 1, 2023'); console.log(today.toString()) // 'Wed Sep 14 2022 17:37:10 GMT+**** (*** Standard Time)' console.log(newYears.toString()) // Sun Jan 01 2023 00:00:00 GMT+**** (*** Standard Time)
Explanation: We Created 2 new date objects, first of the current time, second of the New Year of 2023.
💡 You can pass a date string in the constructor to create a new Date object.
- Get the current hour
- Add X hours to it
- Save the new date
getHours() returns the current hour of the day in 24 Hr Format for the defined date object.
This returns a number from 0 to 23. As these are the only possible values for hours in a day.
setHours() is used to set hours on the date object.
This requires a number from 0 – 23 but you can pass other values too. This allows us to achieve more functionality –
- -1 will set the hour to the last hour of the previous day, date will also change to the previous day
- -2 will set the hour to the hour before the last hour of the previous day, date will also change to the previous day
- Other negative values follow the same trend
- Any values greater than 23 will move the date object to the next day and set the hours accordingly
myDate.setHours(hours) // hours is a required parameter
Let’s see how you can achieve the desired functionality –
const myDate = new Date(); const x = 1; myDate.setHours(myDate.getHours() + x); // adding and saving
Explanation : In this example, we get the current hours, add x hours to it and use the date.setHours method to save the values.
const myDate = new Date('2022-08-10') myDate.setHours(myDate.getHours() + 20); // we are adding 10 to 0 console.log(myDate); // Fri Aug 11 2022 01:30:00 GMT+0530 console.log(myDate.toLocaleString()); // prints the date in your local language // '8/11/2022, 1:30:00 PM' in my case
💡 The results are different from the expected due to the time zone offset being applied automatically , you can use date.toUTCString method to get the UTC time.