Split Time to Hours, Minutes, Seconds in JavaScript


Borislav Hadzhiev

Thu Nov 18 20211 min read

Split Time to Hours, Minutes, Seconds #

To split time to hours, minutes and seconds, call the split() method on the time string, passing it the separator as a parameter, e.g. time.split(':'). The split method will return an array containing 3 strings - the hours, minutes and seconds.

const time = '09:30:46'; const [hours, minutes, seconds] = time.split(':'); console.log(hours); // ๐Ÿ‘‰๏ธ "09" console.log(minutes); // ๐Ÿ‘‰๏ธ "30" console.log(seconds); // ๐Ÿ‘‰๏ธ "46"

The only parameter we passed to the String.split method is the separator, on which we want to split the string, in our case - a colon.

const time = '09:30:46'; // ๐Ÿ‘‡๏ธ ['09', '30', '46'] console.log(time.split(':'));

The method returns an array containing 3 elements - the hours, minutes and seconds.

We used destructuring assignment to assign the values from the array to the hours, minutes and seconds variables.

const [a, b, c] = [1, 2, 3]; console.log(a); // ๐Ÿ‘‰๏ธ 1 console.log(b); // ๐Ÿ‘‰๏ธ 2 console.log(c); // ๐Ÿ‘‰๏ธ 3

When using destructuring assignment the variables get assigned the values from the array in the same order.

The final results consists of 3 strings, which you can manipulate according to your use case.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee