如何将 HH:mm:ss 字符串转换为 Javascript Date 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13802587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a HH:mm:ss string to to a Javascript Date object?
提问by Yosef
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 IE8, Chrome, and Firefox)?
我有一个HH:mm:ss
格式的动态字符串(例如18:19:02
)。如何将字符串转换为 Javascript 日期对象(在 IE8、Chrome 和 Firefox 中)?
I tried the following:
我尝试了以下方法:
var d = Date.parse("18:19:02");
document.write(d.getMinutes() + ":" + d.getSeconds());
回答by Christoph
You cannot create a Date Object directly just from a time like HH:mm:ss
.
您不能仅从像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)
Now you have a Date object which contains the time you specified + the current date and timezone of your client.
现在您有一个 Date 对象,其中包含您指定的时间 + 客户端的当前日期和时区。
回答by silly
try this (without jquery and date object (its only a time))
试试这个(没有 jquery 和 date 对象(它只是一次))
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);
}
回答by Anders H.
Perhaps the Date object is never properly set because of missing date. This should work:
也许由于缺少日期,Date 对象从未正确设置。这应该有效:
var d = new Date("1970-01-01 18:19:02");
document.write(d.getMinutes() + ":" + d.getSeconds());