Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a HH:mm:ss string to a JavaScript Date object?

I have dynamic string with a HH:mm:ss format (e.g. 18:19:02). How can the string be converted into a JavaScript Date object (in Internet Explorer 8, Chrome, and Firefox)?

I tried the following:

   var d = Date.parse("18:19:02");
   document.write(d.getMinutes() + ":" + d.getSeconds());
like image 976
Ben Avatar asked Dec 10 '12 14:12

Ben


2 Answers

You cannot create a Date Object directly just from a time like HH:mm:ss.

However - assuming you want the current date(the day portion of the Date object being today) or it doesn't matter for your case - you could do the following:

let d = new Date(); // Creates a Date Object using the clients current time

let [hours, minutes, seconds] = "18:19:02".split(':');

d.setHours(+hours); // Set the hours, using implicit type coercion
d.setMinutes(minutes); // can pass Number or String - doesn't really matter
d.setSeconds(seconds);

// If needed, you could also adjust date and time zone

console.log(d.toString()); //Outputs desired time (+current day/timezone)

Now you have a Date object which contains the time you specified plus the current date and timezone of your client.

like image 165
Christoph Avatar answered Nov 08 '22 10:11

Christoph


Try this (without jQuery and a date object (it's only a time)):

var
    pieces = "8:19:02".split(':')
    hour, minute, second;

if(pieces.length === 3) {
    hour = parseInt(pieces[0], 10);
    minute = parseInt(pieces[1], 10);
    second = parseInt(pieces[2], 10);
}
like image 42
silly Avatar answered Nov 08 '22 11:11

silly