如何将毫秒转换为日期字符串? [英] How to convert milliseconds to a date string?
问题描述
我从服务器得到一个毫秒的字符串,如下所示:1345623261。
I get a miliseconds string from the server like this: 1345623261.
我如何将其转换成正常的日期格式,例如30.08.2012?
How can i convert this into a normal date format, e.g. 30.08.2012?
我尝试使用 setMilliseconds
,像这样:
new Date().setMilliseconds(time_posted).toLocaleString();
但这不行。如何做?
推荐答案
假设 time_posted
是一个表示时间戳的数字,以秒为单位(以位数表示) - 将其乘以1000,以毫秒为单位,并将结果传递给 Date
的构造函数:
Assuming time_posted
is 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:
(new Date(time_posted * 1000)).toLocaleString();
// -> "Wed Aug 22 2012 11:14:21 GMT+0300 (Jerusalem Daylight Time)"
这更进一步,实现了更接近您在问题中表达的结果,您可以使用 toLocaleDateString()
,这将产生一个更人性化的形式:
To take this a bit further and achieve a result closer to what you denoted in your question, you can use toLocaleDateString()
, which will produce a more human-readable form:
(new Date(time_posted * 1000)).toLocaleDateString();
// -> "Wednesday, August 22, 2012"
参考
-
日期
在Mozilla开发人员网络 Date
on Mozilla Developer Network
Reference
这篇关于如何将毫秒转换为日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!