Can anyone give me a simple JavaScript code block that will allow me to display the local time minus 2 hours?
To subtract hours from a given timestamp, we are going to use the datetime and timedelta classes of the datetime module. Step 1: If the given timestamp is in a string format, then we need to convert it to the datetime object. For that we can use the datetime. strptime() function.
To subtract hours from a date:Use the getHours() method to get the hours of the specific date. Use the setHours() method to set the hours for the date. The setHours method takes the hours as a parameter and sets the value for the date.
Subtract from another date object
var d = new Date(); d.setHours(d.getHours() - 2);
According to Javascript Date Documentation, you can easily do this way:
var twoHoursBefore = new Date(); twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);
And don't worry about if hours you set will be out of 0..23
range. Date() object will update the date accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With