Menu

gitpiper

formatSeconds javascript Code Snippet in 2023

datemathstringintermediate

Last Updated: 28 January 2023

Returns the ISO format of the given number of seconds.

  • Divide s with the appropriate values to obtain the appropriate values for hour, minute and second.
  • Store the sign in a variable to prepend it to the result.
  • Use Array.prototype.map() in combination with Math.floor() and String.prototype.padStart() to stringify and format each segment.
  • Use String.prototype.join(':') to combine the values into a string.
const formatSeconds = s => { const [hour, minute, second, sign] = s > 0 ? [s / 3600, (s / 60) % 60, s % 60, ''] : [-s / 3600, (-s / 60) % 60, -s % 60, '-']; return ( sign + [hour, minute, second] .map(v => `${Math.floor(v)}`.padStart(2, '0')) .join(':') ); };
formatSeconds(200); // '00:03:20' formatSeconds(-200); // '-00:03:20' formatSeconds(99999); // '27:46:39'

javascript snippet similar to formatSeconds For You in January 2023

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2023 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️