为了能够做到这一点,应该将 HH:MM:SS 格式的字符串转换为 JavaScript 时间。
首先,我们可以使用正则表达式 (RegEx) 正确提取该字符串中的值。
let timeString = "01:12:33";
使用正则表达式提取值
let regExTime = /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])/;
let regExTimeArr = regExTime.exec(timeString); // ["01:12:33", "01", "12", "33", index: 0, input: "01:12:33", groups: undefined]
将 HH、MM 和 SS 转换为毫秒
let timeHr = regExTimeArr[1] * 3600 * 1000;
let timeMin = regExTimeArr[2] * 60 * 1000;
let timeSec = regExTimeArr[3] * 1000;
let timeMs = timeHr + timeMin + timeSec; //4353000 -- this is the time in milliseconds.
对于另一个时间点,必须给出一个参考时间。
例如,
let refTimeMs = 1577833200000 //Wed, 1st January 2020, 00:00:00;
上面的值是自纪元时间(1970 年 1 月 1 日 00:00:00)以来经过的毫秒数
let time = new Date (refTimeMs + timeMs); //Wed Jan 01 2020 01:12:33 GMT+0100 (West Africa Standard Time)