JavaScript || How To Get Timespan Between Two Dates & Convert Time From Seconds Into Years, Days, Hours, Minutes & Seconds Using Vanilla JavaScript

The following is a module with functions which demonstrates how to get the timespan between two dates and convert time from seconds into years, days, hours, minutes and seconds using vanilla JavaScript.

This page also demonstrates how to convert time from -seconds- into HH::MM::SS (hours, minutes seconds) format. So for example, if you had an input time of 9630 seconds, the program would display the converted time of 2 hours, 40 minutes, and 30 seconds.

Using simple math, this function utilizes the modulus operator, and the division operator during the conversion process.


1. Get Timespan – Dates

The example below demonstrates the use of ‘Utils.getTimespan‘ to get the timespan between two dates and return the time difference in years, days, hours, minutes and seconds.


2. Get Timespan – Seconds

The example below demonstrates the use of ‘Utils.getTimespan‘ to get the timespan from seconds and return the timespan in years, days, hours, minutes and seconds.


3. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply