可以使用Date对象中的方法来将时间戳转换为日期。具体的实现如下:
"2023-7-14 16:29:44"
const times = new Date().getTime(); // 获取当前时间戳
console.log(times,"times"); //1689323384469 'times'
const date = new Date(times); // 根据时间戳创建Date对象
console.log(date,"date"); // Fri Jul 14 2023 16:29:44 GMT+0800 (中国标准时间) 'date'
const year = date.getFullYear(); // 获取年份
const month = date.getMonth() + 1; // 获取月份,需要加1
const day = date.getDate(); // 获取日期
const hour = date.getHours(); // 获取小时
const minute = date.getMinutes(); // 获取分钟
const second = date.getSeconds(); // 获取秒数
const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`; // 拼接成格式化后的日期字符串
console.log(year,"year"); //2023 'year'
console.log(month,"month"); //7 'month'
console.log(day,"day"); //14 ‘day’
console.log(hour,"hour"); // 16 ‘hour’
console.log(minute,"minute"); //29 'minute'
console.log(second,"second"); //44 'second'
console.log(formattedDate); // 输出:2023-7-14 16:29:44
在上面的代码中,我们使用了Date对象中的getFullYear、getMonth、getDate、getHours、getMinutes和getSeconds方法获取年、月、日、小时、分钟和秒数,并将它们拼接成一个格式化后的日期字符串,最后通过console.log输出。