我有一个 HH:mm:ss
格式的动态字符串(例如 18:19:02
)。如何将字符串转换为 JavaScript 日期对象(在 Internet Explorer 8、Chrome 和 Firefox 中)?
我尝试了以下方法:
var d = Date.parse("18:19:02");
document.write(d.getMinutes() + ":" + d.getSeconds());
最佳答案
您不能直接从像 HH:mm:ss
这样的时间创建日期对象。
但是 - 假设您想要当前日期(Date 对象的日期部分是今天)或者这对您的情况无关紧要 - 您可以执行以下操作:
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)
现在您有一个 Date 对象,其中包含您指定的时间以及您客户的当前日期和时区。
关于javascript - 如何转换 HH :mm:ss string to a JavaScript Date object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13802587/