// 将时间戳转换为可读的日期格式
function timestampToDateString(timestamp) {
// 创建一个新的 Date 对象,传入时间戳(单位:毫秒)
const date = new Date(timestamp);
// 获取年份、月份(注意:月份从0开始,所以要加1)、日期
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // 确保月份是两位数
const day = String(date.getDate()).padStart(2, '0'); // 确保日期是两位数
// 获取小时、分钟、秒
const hours = String(date.getHours()).padStart(2, '0'); // 确保小时是两位数
const minutes = String(date.getMinutes()).padStart(2, '0'); // 确保分钟是两位数
const seconds = String(date.getSeconds()).padStart(2, '0'); // 确保秒是两位数
// 返回格式化的日期字符串
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 示例使用
const timestamp = Date.now(); // 获取当前时间的时间戳
console.log(timestampToDateString(timestamp)); // 输出类似:2023-10-05 14:48:32
timestampToDateString
函数:该函数接收一个时间戳作为参数,并将其转换为 YYYY-MM-DD HH:MM:SS
格式的字符串。new Date(timestamp)
:创建一个新的 Date
对象,用于处理时间戳。JavaScript 的 Date
对象默认以毫秒为单位。getFullYear()
、getMonth()
、getDate()
:分别获取年份、月份和日期。注意,月份是从0开始的,因此需要加1。padStart(2, '0')
:确保月份、日期、小时、分钟和秒都是两位数,不足两位时前面补0。Date.now()
:返回当前时间的时间戳(以毫秒为单位)。上一篇:js 点击空白区域触发事件
下一篇:js push 数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站