JavaScript 如何将UNIX时间戳转换为时间
在本文中,我们将介绍两种方法来将UNIX时间戳转换为时间:
方法1:使用toUTCString()方法
由于JavaScript的工作单位是毫秒,因此在进行转换之前需要将时间乘以1000转换为毫秒。然后将该值传递给Date()函数,以创建一个新的Date对象。使用toUTCString()方法将Date对象表示为字符串的UTC时间格式。可以通过提取从倒数第11个字符到倒数第4个字符之间的字符来获取该日期字符串的时间。可以使用slice()函数进行提取。该字符串是UNIX时间戳的时间表示。
语法:
dateObj = new Date(unixTimestamp * 1000);
utcString = dateObj.toUTCString();
time = utcString.slice(-11, -4);
示例:
function convertTimestamptoTime() {
let unixTimestamp = 10637282;
// Convert to milliseconds and
// then create a new Date object
let dateObj = new Date(unixTimestamp * 1000);
let utcString = dateObj.toUTCString();
let time = utcString.slice(-11, -4);
console.log(time);
}
convertTimestamptoTime();
输出
2:48:02
方法2:获取独立的小时、分钟和秒
由于JavaScript以毫秒为单位工作,因此在进行转换之前需要将时间乘以1000将其转换为毫秒。然后将该值传递给 Date() 函数来创建一个新的Date对象。从Date对象中提取出时间的每个部分。使用 getUTCHours()方法 从日期中提取出UTC小时的值。使用 getUTCMinutes()方法 从日期中提取出UTC分钟的值。使用 getUTCSeconds()方法 从日期中提取出UTC秒的值。通过使用 toString()方法 将这些值中的每一个转换为字符串,并在值为一位数时使用 padStart()方法 在前面填充一个额外的’0’。然后,使用冒号(:)作为分隔符将各个部分连接在一起。这个字符串是UNIX时间戳的时间表示。
语法:
dateObj = new Date(unixTimestamp * 1000);
// Get hours from the timestamp
hours = dateObj.getUTCHours();
// Get minutes part from the timestamp
minutes = dateObj.getUTCMinutes();
// Get seconds part from the timestamp
seconds = dateObj.getUTCSeconds();
formattedTime = hours.toString()
.padStart(2, '0') + ':'
+ minutes.toString()
.padStart(2, '0') + ':'
+ seconds.toString()
.padStart(2, '0');
示例:
function convertTimestamptoTime() {
let unixTimestamp = 10637282;
// Convert to milliseconds and
// then create a new Date object
let dateObj = new Date(unixTimestamp * 1000);
// Get hours from the timestamp
let hours = dateObj.getUTCHours();
// Get minutes part from the timestamp
let minutes = dateObj.getUTCMinutes();
// Get seconds part from the timestamp
let seconds = dateObj.getUTCSeconds();
let formattedTime = hours.toString().padStart(2, '0')
+ ':' + minutes.toString().padStart(2, '0')
+ ':' + seconds.toString().padStart(2, '0');
console.log(formattedTime);
}
convertTimestamptoTime();
输出
02:48:02