/ Published in: JavaScript
A simple function for taking a number of seconds and displaying it as separate units of time. Designed to be modified to support any consistent units of time as it automatically sorts units by their size and calculates remaining seconds at each step. Supports hiding units after a specified unit.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function secondsSeparated(seconds, lastUnit) { if ( ! $.isNumeric(seconds)) { return ""; } // Define units and how many seconds they represent var units = {ms: 1/1000, s: 1, m: 60}; units.h = units.m * 60; units.d = units.h * 12; units.w = units.d * 7; units.y = units.d * 365; // Calculate and append units in the order of largest to smallest var unitsSorted = Object.keys(units); unitsSorted.sort(function (a, b) { // This sorts it descending return units[b] - units[a]; }); var sign = (seconds < 0 ? '-' : ''); if (seconds < 0) { seconds = Math.abs(seconds); } var secondsRemaining = seconds; var formattedValue = ''; for (var u in unitsSorted) { var unit = unitsSorted[u]; var unitSeconds = units[unit]; var value = 0; if (unitSeconds <= secondsRemaining) { value = Math.floor(secondsRemaining / unitSeconds); secondsRemaining = secondsRemaining % unitSeconds; } else if (unit !== 's' && (formattedValue === '' || unit === 'ms')) { if (unit === lastUnit) { break; } // Don't display zero units until a non-zero unit has been displayed continue; } formattedValue += value + unit + ' '; if (unit === lastUnit) { break; } } return sign + formattedValue.trim(); }