If we have two variables A and B, and the both of their values is time, how do we measure the distance between those variables?
In other word, let’s say variable A is 6 o’clock and B is 9 o’clock. So between 6 and 9 is 3 hours distance and we know that by subtracting 6 from 9.
I have two variable in this example. First called “starttime” and its value is the time my document loaded on browser. The second variable called “now” and its value is the time I click a button in my page. Then, when I click that button, within a function I created, the variable “starttime” is subtracted from variable “now” and the result displayed in an alert message (in milliseconds).
Press this button to show how much milliseconds elapsed from a moment document is loaded until now.
Here is the source code:
var starttime = Date.now();
now = Date.now();
alert("Elapsed in millisec: "+(now-starttime));
<p>Press this button to show how much milliseconds elapsed from a moment document is loaded until now.</p>
The next thing we can do is to convert milliseconds into seconds, minuts, hours and so forth. This step is important if we want to calculate, for example, how long ago a user post his/her message, like “3 minutes ago…”, “4 hours and 40 minutes ago…” and so on.