Calculate time between two dates
- » Overview
- » Example 1
- » Usage & args
- » Example 2
- » Notes
Overview
This script returns the number of seconds, minutes, hours, days, weeks, months or years between two given dates - or between one given date and the present moment.
Example 1
Click here for the number of days between 2nd Feb 1943 and 23rd Nov 1946.
Here's the code behind this example, applied to the link's href:
alert(between2Dates('02/05/1943 00:00:00', '23/11/1946 00:00:00', 'days'))
Usage & args
Call the main function and pass it the arguments necessary for your calculation.
between2Dates(date1, date2, unit);
date1 (string) - a string representing the start date, in the format dd/mm/yyyy hh:mm:ss OR the string 'now', to denote the present moment.
date2 (string) - as with date1
unit (string) - a string representing the unit of measurement you require - either 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months' or 'years'
Example 2
Click here for the number of hours between now and Christmas day 1543.
Here's the code behind this example, applied to the link's href:
alert(between2Dates('25/12/1543 00:00:00', 'now', 'hours'))
Notes
Requests where unit == months
In these cases, months are calculated as containing an average of 4.3 weeks. Since months do not have a consistent number of days, such requests may be contentious.
The following, for example, will alert 1.02, not 1 as might be expected, as the number of weeks between 29 May and 29 June is slightly more than the 4.3 average.
alert(between2Dates('29/05/1980 00:00:00', '29/06/1980 00:00:00', 'months'));
Comments (0)