Date object to check whether a particular date is before or after the other date.
Having said that, the
Date does not provide any direct way to find out exact difference between the two dates in terms of days, hours, minutes and so on. However using some of the existing functions of the
In the above code we have taken advantage of the function
date.getTime() which returns the number of milliseconds since 1970/01/01. This forms a common baseline to compare 2 dates. Here is quick summary of the code.
- Style and Body block is added just as a need to render the results to demonstrate the date difference in the required format.
- There are three functions in the Script block which is of our interest in this example.
init() :This function is called on load to populate/render the values of dates and their diff.
getDatesDifference(dateFrom, dateTo) :This function accepts 2 date objects as an input parameter. Retrieves the milliseconds of both the dates to get the difference. This difference of milliseconds is passed to the next function for formatting.
getFormattedDelta(deltaMillis) :This function accepts delta milliseconds as an input and formats it in the required string. Days, Hours, Minutes, Seconds and Milliseconds are calculated from the delta milliseconds using simple arithmetic.
You may want to paste the above code as an html file and see the results in the browser. Try updating the inputs of variable
newDate to see the variations. Here is a screen shot of browser after loading HTML with the above code.
This is just an example, and one can think of returning the diff string in some other reusable format from the function
getFormattedDelta(). Perhaps it could be delimited string or XML or JSON.
Date object can be found here.