Convert a Unix timestamp to time in JavaScript

Convert a Unix timestamp to time in JavaScript

技术背景

Unix时间戳是从1970年1月1日00:00:00 UTC开始所经过的秒数。在JavaScript中,Date对象使用的是从该时间点开始的毫秒数。因此,在将Unix时间戳转换为JavaScript中的时间时,需要将秒数乘以1000转换为毫秒数。

实现步骤

1. 使用new Date()对象

这是JavaScript内置的方法,以下是示例代码:

1
2
3
4
5
6
7
let unix_timestamp = 1549312452;
var date = new Date(unix_timestamp * 1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);

2. 使用Intl.DateTimeFormat

这是现代的解决方案,更具国际化支持:

1
2
3
4
5
6
7
8
var options = {
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
var intlDate = new Intl.DateTimeFormat(undefined, options);
var timeStamp = 1412743273;
console.log(intlDate.format(new Date(1000 * timeStamp)));

3. 使用第三方库

Moment.js

1
2
3
4
const moment = require('moment');
const timestampObj = moment.unix(1504052527183);
const result = timestampObj.format("HH/mm/ss");
console.log(result);

Day.js

1
2
3
const dayjs = require('dayjs');
const result = dayjs(1504052527183).format("HH/mm/ss");
console.log(result);

核心代码

自定义格式化函数

1
2
3
4
5
6
7
8
9
function convertTime(timestamp, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = timestamp ? new Date(timestamp * 1000) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(typeof separator!== 'undefined'? separator : ':');
}

从特定起始时间转换

1
2
3
4
5
function ConvertUnixTimeToDateForLeap(UNIX_Timestamp) {
var dateObj = new Date(1980, 0, 1, 0, 0, 0, 0);
dateObj.setSeconds(dateObj.getSeconds() + UNIX_Timestamp);
return dateObj;
}

最佳实践

  • 性能考虑:如果对性能要求较高,尽量使用原生的Date对象方法,避免引入大型的第三方库。
  • 国际化支持:如果需要支持不同的语言和地区,建议使用Intl.DateTimeFormat
  • 代码简洁性:对于简单的时间格式化需求,可以使用自定义的格式化函数。

常见问题

1. 零填充问题

当小时、分钟或秒数为个位数时,可能会出现缺少前导零的问题。可以使用pad函数进行处理:

1
2
3
function pad(input) {
return input < 10? "0" + input : input;
}

2. 时间戳单位问题

Unix时间戳是秒为单位,而JavaScript的Date对象使用的是毫秒为单位,需要将Unix时间戳乘以1000。

3. 第三方库的兼容性和维护性

像Moment.js已经逐渐被弃用,建议选择更现代和轻量级的库,如Day.js。


Convert a Unix timestamp to time in JavaScript
https://119291.xyz/posts/convert-unix-timestamp-to-time-in-javascript/
作者
ww
发布于
2025年5月28日
许可协议