Format Seconds as time units


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. function secondsSeparated(seconds, lastUnit) {
  2. if ( ! $.isNumeric(seconds)) {
  3. return "";
  4. }
  5.  
  6. // Define units and how many seconds they represent
  7. var units = {ms: 1/1000, s: 1, m: 60};
  8. units.h = units.m * 60;
  9. units.d = units.h * 12;
  10. units.w = units.d * 7;
  11. units.y = units.d * 365;
  12.  
  13. // Calculate and append units in the order of largest to smallest
  14. var unitsSorted = Object.keys(units);
  15. unitsSorted.sort(function (a, b) {
  16. // This sorts it descending
  17. return units[b] - units[a];
  18. });
  19.  
  20. var sign = (seconds < 0 ? '-' : '');
  21. if (seconds < 0) {
  22. seconds = Math.abs(seconds);
  23. }
  24. var secondsRemaining = seconds;
  25. var formattedValue = '';
  26. for (var u in unitsSorted) {
  27. var unit = unitsSorted[u];
  28. var unitSeconds = units[unit];
  29. var value = 0;
  30. if (unitSeconds <= secondsRemaining) {
  31. value = Math.floor(secondsRemaining / unitSeconds);
  32. secondsRemaining = secondsRemaining % unitSeconds;
  33. } else if (unit !== 's' && (formattedValue === '' || unit === 'ms')) {
  34. if (unit === lastUnit) {
  35. break;
  36. }
  37. // Don't display zero units until a non-zero unit has been displayed
  38. continue;
  39. }
  40. formattedValue += value + unit + ' ';
  41.  
  42. if (unit === lastUnit) {
  43. break;
  44. }
  45. }
  46. return sign + formattedValue.trim();
  47. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.