JavaScript 时间戳转年月日时分秒格式函数
以下是一个 JavaScript 函数,它接受一个时间戳作为参数,并返回该时间戳的年、月、日、小时、分钟和秒。
function getFormattedDate(timestamp) {
const date = new Date(timestamp * 1000);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
调用该函数时,您可以将当前时间戳作为参数传递,如下所示:
const now = Math.floor(Date.now() / 1000); // 当前时间戳,单位为秒
const formattedDate = getFormattedDate(now);
console.log(formattedDate); // 输出类似于 '2022-03-23 14:30:00' 的字符串
原文地址: https://www.cveoy.top/t/topic/n9Qs 著作权归作者所有。请勿转载和采集!