Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

jquery - 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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

However - assuming you want the actual date(day) 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(':'); // Using ES6 destructuring
// var time = "18:19:02".split(':'); // "Old" ES5 version

d.setHours(+hours); // Set the hours, using implicit type coercion
d.setMinutes(minutes); // You can pass Number or String. It doesn't really matter
d.setSeconds(seconds);
// If needed, adjust date and time zone

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...