Martin Milo

A blog about software development, architecture, and more.

Weekly updates on latest blog posts, thoughts and useful stuff.

Split time to hours, minutes and seconds in Javascript

javascript basics

Split time to hours, minutes and seconds in Javascript can be achieved by using a method called split() on the time string with the colon : as a parameter.

const timeString = '08:15:34'

const [hrs, mins, secs] = timeString.split(':')

console.log(hrs) // ๐Ÿ‘‰๏ธ '08'
console.log(mins) // ๐Ÿ‘‰๏ธ '15'
console.log(secs) // ๐Ÿ‘‰๏ธ '34'

As said, we need to pass a colon (:) as a parameter, so that the time string is split correctly.

Alright but how do we get the time string in the first place?

const currentTimeString = new Date().toLocaleTimeString()

console.log(currentTimeString) // ๐Ÿ‘‰๏ธ 08:15:34 (in my case)

Please be aware that the toLocaleTimeString() method can behave differently depending on the browser's implementation (mostly older browsers).

Destructuring assignment makes the syntax more neat. When using destructuring assignment, the variables get assigned in the order in which the array holds it's items.

Let's have a look at the example without destructuring assignment if you're not familiar with it.

const timeString = '08:15:34'

const parts = timeString.split(':')

const hrs = parts[0]
const mins = parts[1]
const secs = parts[2]

console.log(hrs) // ๐Ÿ‘‰๏ธ '08'
console.log(mins) // ๐Ÿ‘‰๏ธ '15'
console.log(secs) // ๐Ÿ‘‰๏ธ '34'

It's the same example as the one above but as you can see, we're not using destructuring assignment which makes the code a bit longer.

Most of the time, you might want to convert each time component (hours, minutes and seconds) to number. Keep in mind that when you split a String, each part is going to be String as well even if it only consists of numbers.

const timeString = '08:15:34'

const parts = timeString.split(':')

console.log(parts[0]) // ๐Ÿ‘‰๏ธ '08'
// The output is 08 and type of string - NOT a number!

You can convert each part to a number by using Number constructor but there's even better way to do so if we use our example with destructuring assignment.

const timeString = '08:15:34'

const [hrs, mins, secs] = timeString.split(':').map(Number)
// Now all items within the array will be converted to a Number (type)

console.log(hrs) // ๐Ÿ‘‰๏ธ 8
console.log(mins) // ๐Ÿ‘‰๏ธ 15
console.log(secs) // ๐Ÿ‘‰๏ธ 34

We are using a Array.prototype.map() function - we iterate over the time parts and convert each item to a number. By passing Number directly to the map, we've just shortened the following code .map(item => Number(item)).

Martin Milo
The Author Martin Milo

Seasoned full-stack developer with years of startup experience at Wonderway.io, now focused on BE architecture and DevX at Become1.de. Pragmatic at building own web and native apps. Writing software-related blog posts and teaching.