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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// Get Timespan - Dates <script> (() => { // Declare dates let date1 = new Date('1987-07-28 19:22:31'); let date2 = new Date('1991-01-27 10:19:28'); // Get the timespan let timespan = Utils.getTimespan(date1, date2); // Display result console.log(`Date 1: ${date1.toLocaleString()}`); console.log(`Date 2: ${date2.toLocaleString()}`); console.log(timespan.toString()); console.log(timespan); })(); </script> // expected output: /* Date 1: 7/28/1987, 7:22:31 PM Date 2: 1/27/1991, 10:19:28 AM 3 years, 183 days, 14 hours, 56 minutes, 57 seconds { "years": 3, "days": 183, "hours": 14, "minutes": 56, "seconds": 57, "milliseconds": 0, "totalYears": 3.5030763888888887, "totalDays": 1278.6228819444445, "totalHours": 30686.949166666665, "totalMinutes": 1841216.95, "totalSeconds": 110473017, "totalMilliseconds": 110473017000 } */ |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// Get Timespan - Seconds <script> (() => { // Declare seconds let seconds = 9630; // Get the timespan let timespan = Utils.getTimespan(seconds); // Display result console.log(`Seconds: ${seconds}`); console.log(timespan.toString()); console.log(timespan); })(); </script> // expected output: /* Seconds: 9630 2 hours, 40 minutes, 30 seconds { "years": 0, "days": 0, "hours": 2, "minutes": 40, "seconds": 30, "milliseconds": 0, "totalYears": 0.000305365296803653, "totalDays": 0.11145833333333334, "totalHours": 2.675, "totalMinutes": 160.5, "totalSeconds": 9630, "totalMilliseconds": 9630000 } */ |
3. Utils Namespace
The following is the Utils.js Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jan 1, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.js // Description: Javascript that handles general utility functions // ============================================================================ /** * NAMESPACE: Utils * USE: Handles general utility functions. */ var Utils = Utils || {}; (function(namespace) { 'use strict'; // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: getTimespan * USE: Returns the timespan between two dates, or a time value in seconds * @param start: The starting time * @param end: The ending time * @return: An object which contains information about the timespan */ exposed.getTimespan = (start, end = null) => { // Get the seconds let seconds = Number(start); if (isDate(start) && isDate(end)) { seconds = exposed.getDurationSeconds(start, end); } // Convert seconds to time let timespan = {}; let remainingTime = seconds; for (const def of conversion) { // Get time conversion timespan[def.key] = Math.floor(remainingTime / def.value); remainingTime %= def.value; // Add additional info let additionalKey = `total${capitalize(def.key)}`; timespan[additionalKey] = seconds / def.value; } // Add additional info timespan.toString = () => { let string = ''; for (const def of conversion) { let value = timespan[def.key] if (value != 0) { let name = def.key; if (name.endsWith('s')) { name = name.substring(0, name.length - 1); } string += string.length > 0 ? ',' : ''; string += ` ${value} ${name}${value == 1 ? '' : 's'}`; } } return string.trim(); } return timespan; } /** * FUNCTION: getDurationSeconds * USE: Returns the number of seconds between the two dates * @param dateStart: The starting date * @param dateEnd: The ending date * @return: The number of seconds between the two dates */ exposed.getDurationSeconds = (dateStart, dateEnd) => { let timeStart = dateStart ? treatAsUTC(dateStart).getTime() : 0; let timeEnd = dateEnd ? treatAsUTC(dateEnd).getTime() : 0; return (timeEnd - timeStart) / 1000; } let treatAsUTC = (date) => { let result = new Date(date); result.setMinutes(result.getMinutes() - result.getTimezoneOffset()); return result; } let isDate = (expression) => { return expression && (expression instanceof Date); } let capitalize = (string) => { return string.charAt(0).toUpperCase() + string.substring(1); } // Set the time conversion definitions (from seconds) const conversion = [ {key: 'years', value: 60 * 60 * 24 * 365}, {key: 'days', value: 60 * 60 * 24}, {key: 'hours', value: 60 * 60}, {key: 'minutes', value: 60}, {key: 'seconds', value: 1}, {key: 'milliseconds', value: 1 / 1000} ]; (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Utils)); // http://programmingnotes.org/ |
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.
Leave a Reply