Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract 2 hours from user's local time?

Can anyone give me a simple JavaScript code block that will allow me to display the local time minus 2 hours?

like image 342
Etienne Avatar asked Feb 09 '11 09:02

Etienne


People also ask

How do I subtract hours from a timestamp?

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.

How to subtract hours in JavaScript?

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.


2 Answers

Subtract from another date object

var d = new Date();  d.setHours(d.getHours() - 2); 
  • Complete reference list for Date object
like image 65
BrunoLM Avatar answered Sep 17 '22 17:09

BrunoLM


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.

like image 43
Kostanos Avatar answered Sep 17 '22 17:09

Kostanos