如何在JavaScript中将此日期字符串转换为毫秒

时间:2018-09-18 08:22:10

标签: javascript date milliseconds

我可以从后台获取日期字符串,格式为'Tue Sep 18 14:42:56 SGT 2018'。我想在JavaScript中将其转换为毫秒。

我已经尝试过Date.parse('Tue Sep 18 14:42:56 SGT 2018'),但是它将返回NaN

有人可以帮忙吗?预先感谢。

2 个答案:

答案 0 :(得分:1)

这是javascript无法识别的有效日期字符串,告诉后台办公室人员更改日期格式,更好的方法是直接给您毫秒。

答案 1 :(得分:1)

You can also do a bit of formatting to that string before you parse it. If you split it, you can build a valid format.

var dateString = 'Tue Sep 18 14:42:56 SGT 2018';
var pieces = dateString.split(" ");
var date = new Date(pieces[2]+" "+pieces[1]+" "+pieces[5]+" "+pieces[3]);
date.setHours(date.getHours()-8); // SGT to UTC
console.log(date.toString());

I created a jsbin for you. https://jsbin.com/jugonur/edit?html,js,console,output

See the valid formats here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse