Converting a time string to a time value in javascript

Viewed 27500

I have a string that looks like "01:12:33" which is HH:MM:SS format. How can I convert that to a time value in JS?

I've tried the new Date() constructor and setting the year and day values to 0, then doing getTime(), but I am not having any lucky.

3 Answers

Prefix it with a date:

var hms = "01:12:33";
var target = new Date("1970-01-01 " + hms);
console.log(target);

There target.getTime() will give you the number of milliseconds since the start of the day;

Or, if you need it to be today's date:

var now = new Date();
var nowDateTime = now.toISOString();
var nowDate = nowDateTime.split('T')[0];
var hms = '01:12:33';
var target = new Date(nowDate + 'T' + hms);
console.log(target);

There target.getTime() will give you the number of milliseconds since the epoch.

You can add the following function that does the job for you :

function getDateFromHours(time) {
    time = time.split(':');
    let now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...time);
}
console.log(getDateFromHours('01:12:33'));

To be able to do this, there should be a conversion of the string in HH:MM:SS format to JavaScript time.

Firstly, we can use Regular Expression (RegEx) to properly extract the values in that string.

let timeString = "01:12:33";

Extract values with RegEx

let regExTime = /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])/;
let regExTimeArr = regExTime.exec(timeString); // ["01:12:33", "01", "12", "33", index: 0, input: "01:12:33", groups: undefined]

Convert HH, MM and SS to milliseconds

let timeHr = regExTimeArr[1] * 3600 * 1000;
let timeMin = regExTimeArr[2] * 60 * 1000;
let timeSec = regExTimeArr[3] * 1000;

let timeMs = timeHr + timeMin + timeSec; //4353000 -- this is the time in milliseconds.

In relation to another point in time, a reference time has to be given.

For instance,

let refTimeMs = 1577833200000  //Wed, 1st January 2020, 00:00:00; 

The value above is is the number of milliseconds that has elapsed since the epoch time (Jan 1, 1970 00:00:00)

let time = new Date (refTimeMs + timeMs); //Wed Jan 01 2020 01:12:33 GMT+0100 (West Africa Standard Time)
Related