如何在Javascript中从Unix时间戳获取可读日期?

5
在我的Javascript代码中,我有一个Unix时间戳(例如“1318305600000”),我需要通过Javascript将其转换为可读的日期格式。
我该如何操作?
2个回答

9
alert(new Date(1318305600000))

可以,但是当我将其放在变量中(例如 new Date(x))时,会出现“无效日期”的错误。当我将 x 输出到 Chrome 控制台时,它显示为“1318910400000.00”。 - KallDrexx
那看起来像一个浮点数。尝试使用 parseInt(x, 10) 将其截断为整数。 - SLaks

8
var date = new Date(unix_timestamp*1000);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
// will display time in 21:00:00 format
var formattedTime = hours + ':' + minutes + ':' + seconds;

完整参考资料

getDate()   Returns the day of the month (from 1-31)
getDay()    Returns the day of the week (from 0-6)
getFullYear()   Returns the year (four digits)
getHours()  Returns the hour (from 0-23)
getMilliseconds()   Returns the milliseconds (from 0-999)
getMinutes()    Returns the minutes (from 0-59)
getMonth()  Returns the month (from 0-11)
getSeconds()    Returns the seconds (from 0-59)
getTime()   Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the time difference between GMT and local time, in minutes
getUTCDate()    Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear()    Returns the year, according to universal time (four digits)
getUTCHours()   Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds()    Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth()   Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
getYear()   Deprecated. Use the getFullYear() method instead

谢谢您的回复。我将其标记为答案,因为它提供了一个很好的参考,可以做更多的事情,而不仅仅是提供默认日期格式。 - KallDrexx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接