Javascript 将unix时间戳转换为javascript日期对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13994083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:21:41  来源:igfitidea点击:

Convert unix timestamp to javascript date Object

javascriptdateunix-timestamp

提问by jamjam

Am working with json api that represents dates like this

我正在使用表示这样的日期的 json api

"date" : "/Date(1356081900000)/"

I want to turn this into regular javascript Date.

我想把它变成常规的 javascript 日期。

The only way I can think of solving this problem is to do a replace on everything leaving the timestamp which I can then "convert".

我能想到解决这个问题的唯一方法是替换所有留下时间戳的内容,然后我可以“转换”。

This works but it just looks wrong.

这有效,但看起来是错误的。

My question. Can I do this in better way?

我的问题。我能以更好的方式做到这一点吗?

UPDATE

更新

 unix_timestamp = jsonDate.replace('/Date(', '').replace(')/', '');

 newDate = new Date(+unix_timestamp + 1000*3600);

采纳答案by antila

Duplicate of How to format a JSON date?.

重复如何格式化 JSON 日期?.

Accepted solution was:

接受的解决方案是:

var date = new Date(parseInt(jsonDate.substr(6)));

回答by Rahul Tripathi

Try something like this:-

尝试这样的事情:-

 var d = new Date(unix_timestamp*1000);

or

或者

 var d = new Date([UNIX Timestamp] * 1000);

回答by josh3736

The Dateconstructor accepts a Unix timestamp.

Date构造函数接受一个Unix时间戳。

function cleanDate(d) {
    return new Date(+d.replace(/\/Date\((\d+)\)\//, ''));
}

cleanDate("/Date(1356081900000)/"); // => Fri Dec 21 2012 04:25:00 GMT-0500 (EST)