Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a time string to a time value in javascript

Tags:

javascript

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.

like image 201
Milos Avatar asked Oct 05 '17 17:10

Milos


1 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 + hms);
console.log(target);

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

like image 105
cwallenpoole Avatar answered Oct 21 '22 15:10

cwallenpoole