我有一个HH:mm:ss格式的动态字符串(例如18:19:02).如何将字符串转换为Javascript Date对象(在IE8,Chrome和Firefox中)?
我尝试了以下方法:
var d = Date.parse("18:19:02");
document.write(d.getMinutes() + ":" + d.getSeconds());
Run Code Online (Sandbox Code Playgroud)
Chr*_*oph 13
您无法直接创建日期对象HH:mm:ss.
但是(假设您想要实际日期或无所谓!)您可以这样做
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)Run Code Online (Sandbox Code Playgroud)
现在您有一个包含所需时间的日期对象.
试试这个(没有 jQuery 和日期对象(这只是一个时间)):
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);
}
Run Code Online (Sandbox Code Playgroud)