在 javascript 中将时间字符串转换为时间值

问题描述 投票:0回答:3

我有一个看起来像这样的字符串:

"01:12:33"

格式为 HH:MM:SS。

如何将其转换为 JS 中的时间值?

我尝试过

new Date()
构造函数并将年和日值设置为 0,然后执行
getTime()
,但我没有任何运气。

javascript
3个回答
28
投票

在其前面加上日期:

var hms = "01:12:33";
var target = new Date("1970-01-01T" + hms);
console.log(target);

那里

target.getTime()
将为您提供自一天开始以来的毫秒数;

或者,如果您需要今天的日期:

var now = new Date();
var nowDateTime = now.toISOString();
var nowDate = nowDateTime.split('T')[0];
var hms = '01:12:33';
var target = new Date(nowDate + 'T' + hms);
console.log(target);

那里

target.getTime()
将为您提供自纪元以来的毫秒数。


4
投票

您可以添加以下功能来完成您的工作:

function getDateFromHours(time) {
    time = time.split(':');
    let now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...time);
}
console.log(getDateFromHours('01:12:33'));

2
投票

为了能够做到这一点,应该将 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)
© www.soinside.com 2019 - 2024. All rights reserved.