将字符串hh:mm:ss解析为时间戳

时间:2019-10-25 17:03:30

标签: javascript jquery

嘿如何在时间戳中转换字符串

我恢复了时间文本,并将其转换为日期

当我转换为时间戳记时,该值为负数

var timenow=$("#time").text();
var res = timenow.split(":");
var d80 = new Date();
var curr_date = d80.getDate();
var curr_month = d80.getMonth();

var curr_year = d80.getFullYear();
var date1 = new Date(curr_date, curr_month, curr_year, res[0], res[1],res[2]);

console.log(date1);

const timestamp = date1 / 1000;
console.log(timestamp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="time">
00:50:30
</div>

3 个答案:

答案 0 :(得分:0)

您使用Date的构造函数错误。第一个参数是年份:

var date1 = new Date(curr_year, curr_month, curr_date, res[0], res[1],res[2]);

此外,我认为您的代码可以改进:

const [hours, minutes, seconds] = $("#time").text().split(":");

let currentDate = new Date();
currentDate.setHours(hours, minutes, seconds)

const timestamp = currentDate.getTime();
console.log(timestamp);

答案 1 :(得分:0)

在JavaScript中,时间戳是自1970年1月1日起经过的毫秒数(1970年1月1日也称为Unix纪元时间)

在示例代码中,date1是1931-04-11。大约39年了!因此为负值。

构造date1时需要使用正确的格式:

var date1 = new Date(curr_year, curr_month, curr_date, res[0], res[1],res[2]);

EG:

var timenow=$("#time").text();
var res = timenow.split(":");
var d80 = new Date();
var curr_date = d80.getDate();
var curr_month = d80.getMonth();

var curr_year = d80.getFullYear();
//var date1 = new Date(curr_date, curr_month, curr_year, res[0], res[1],res[2]);

var date1 = new Date(curr_year, curr_month, curr_date, res[0], res[1],res[2]);
console.log(date1);

const timestamp = date1 / 1000;
console.log(timestamp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="time">
00:50:30
</div>

答案 2 :(得分:0)

以正确的方式调用日期构造器

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

更多信息:click here

var timenow=$("#time").text();
var res = timenow.split(":");
var d80 = new Date();
var curr_date = d80.getDate();
var curr_month = d80.getMonth();


var curr_year = d80.getFullYear();


var date1 = new Date(curr_year,curr_month, curr_date,res[0], res[1], res[2]);

console.log(date1); //"2019-10-26T01:20:00.000Z"


const timestamp = date1.getTime();// to get timestamp
console.log(timestamp);

let date2 = new Date(timestamp);
console.log(date2); //"2019-10-26T01:20:00.000Z"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="time">
00:50:30
</div>