JavaScript for Time Calculations
In programming for the Web it might become necessary to perform calculations based on the date (or specific future dates) in order to get information to a viewer. Dates and times are handled differently from other numerical values based on the specific rules that they follow (and the irregularities of date and time measurements due to differences in month lengths or leap years). The JavaScript Date Object allows programmers to access the date and time in order to preform calculations.
-
The Date Object
-
The JavaScript Date object is instantiated like other objects, like so:
var d = new Date();
From this variable "d" which represents an instance of a date object, the system time can be accessed through method calls to the object (such as retrieving local date and time, time zone information, and the Coordinated Universal Time).
Different Time Methods
-
from a Date object, the different measures of time can be gathered: hours, minutes, seconds, and day (among others) (Source 1). For example, the programmer can call methods to gather date and time values, such as the current hour (Source 1):
var h = d.getHours();
or, another example:
var m = d.getMinutes();
will return the current minute of the hour (from 1 to 59) (Source 1). For seconds,
var s = d.getSeconds();
will return seconds in a similar format (1 to 59).
-
Return Values
-
For simple time calculations regarding the hour, minutes and seconds, obtaining the base numerical values should be sufficient. Minutes and seconds both return integer values from 0 to 59, so calculating differences should be a simple matter of subtractions. Hours, however, are returned based on the 24 hour clock (Source 1). This means that in order to display results in standard time, additional calculations are required to produce the proper standard time.
Examples
-
As an example:
var d = new Date();
var h1 = d.getHours();
var future_date = 23;
var diff;
if (h1 >= future_date)
{diff = h1 - future_date;}
else
{diff = future_date - h1;}
This example code gets the current hour, and compares it to a future hour through subtraction (the difference being the number of hours between the two times). In order to display an hour in standard time, try this code:
var h2 = d.getHours();
if (h2 > 12)
{h2 = h2 - 12;}
document.write(h2);
-
References
- Photo Credit Comstock/Comstock/Getty Images