Skip to content

Instantly share code, notes, and snippets.

@Deityhub
Created June 20, 2019 04:04
Show Gist options
  • Save Deityhub/b9aa8b867abd7cadb63709cd67fc6bc6 to your computer and use it in GitHub Desktop.
Save Deityhub/b9aa8b867abd7cadb63709cd67fc6bc6 to your computer and use it in GitHub Desktop.
const secondsToHms = value => {
value = Number(value);
let hr = Math.floor(value / 3600),
min = Math.floor((value % 3600) / 60),
sec = Math.floor((value % 3600) % 60);
return (
(hr > 0 ? hr + ":" + (min < 10 ? "0" : "") : "") +
min +
":" +
(sec < 10 ? "0" : "") +
sec
);
};
export default secondsToHms;
@Deityhub
Copy link
Author

This code snippet is used to convert your time from seconds to hour:minute:second format, which is more readable to the user.

@Deityhub
Copy link
Author

/**
 * @description converts seconds to human readable hr min sec format
 * @param {*} value a string or number representing time in seconds
 * @returns a string in the formatted style
 * @example secondsToHms(3600) will return 1hr
 */
const secondsToHms = value => {
    value = Number(value);
    const hr = Math.floor(value / 3600),
        min = Math.floor((value % 3600) / 60),
        sec = Math.floor((value % 3600) % 60);

    const formattedValue = `${hr > 0 ? `${hr} hr` : ''} ${
        min > 0
            ? min < 10
                ? `0${min} min`
                : `${min} min`
            : `${hr > 0 ? '0 min' : ''}`
    } ${sec < 10 ? `${sec > 0 ? `0${sec} sec` : '0 sec'}` : `${sec} sec`}`;
    return formattedValue.trim();
};

module.exports = secondsToHms;

@Deityhub
Copy link
Author

This is an improved version for hr min sec time format

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment