Files
reference/source/_posts/note/javascript/date-time/convert-seconds-to-hh-mm-ss-format.md
T
2022-11-16 14:10:09 +08:00

954 B

title, tags, layout
title tags layout
How to convert seconds to hh:mm:ss format in JavaScript
JavaScript
ES6
one-line
js
Date Time
note

In this Article we will go through how to convert seconds to hh:mm:ss format only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const formatSeconds = s => new Date(s * 1000).toISOString().substr(11, 8);

Parameters s is number of seconds.

Or

const formatSeconds = s => (new Date(s * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];

Or

const formatSeconds = s => [parseInt(s / 60 / 60), parseInt(s / 60 % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1');

Example

formatSeconds(200);     // 00:03:20
formatSeconds(500);     // 00:08:20