Javascript 如何将毫秒转换为日期字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12196689/
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-23 07:22:42  来源:igfitidea点击:

How to convert milliseconds to a date string?

javascriptdatetime

提问by alexh

I get a miliseconds string from the server like this: 1345623261.

我从服务器得到一个毫秒字符串,如下所示:1345623261。

How can i convert this into a normal date format, e.g. 30.08.2012?

我如何将其转换为正常的日期格式,例如 30.08.2012?

I attempted using setMilliseconds, like so:

我尝试使用setMilliseconds,像这样:

new Date().setMilliseconds(time_posted).toLocaleString();

But this doesn't work. How to do that?

但这不起作用。怎么做?

回答by Eliran Malka

Assuming time_postedis a number representing timestamp, which is expressed in seconds (judging by the number of digits) - multiply it by 1000 to get a representation in milliseconds, and pass the result to the Date's constructor:

假设time_posted是一个表示时间戳的数字,以秒表示(根据位数判断) - 将其乘以 1000 以获得以毫秒为单位的表示,并将结果传递给Date构造函数:

(new Date(time_posted * 1000)).toLocaleString();
    // -> "Wed Aug 22 2012 11:14:21 GMT+0300 (Jerusalem Daylight Time)"

To take this a bit further and achieve something closer to what you denoted in the question, use toLocaleDateString(), which will produce a more human-readable form:

为了更进一步并实现更接近您在问题中表示的内容,请使用toLocaleDateString(),这将产生更易于阅读的形式:

(new Date(time_posted * 1000)).toLocaleDateString();
    // -> "Wednesday, August 22, 2012"

Reference

参考