Split Time to Hours, Minutes, Seconds in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 18, 2021

banner

Photo from Unsplash

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.

index.js
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.

index.js
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.

index.js
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.