js将时间戳转换成年月日时分秒
时间: 2024-01-20 11:16:09 浏览: 31
以下是将时间戳转换为年月日时分秒的两种方法:
1. 使用Date对象的toLocaleString()方法:
```javascript
var timestamp = 1612345678; // 时间戳
var date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
var year = date.getFullYear(); // 年份
var month = date.getMonth() + 1; // 月份(注意月份从0开始,需要加1)
var day = date.getDate(); // 日期
var hour = date.getHours(); // 小时
var minute = date.getMinutes(); // 分钟
var second = date.getSeconds(); // 秒钟
var formattedDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
console.log(formattedDate); // 输出:2021-2-3 12:34:38
```
2. 使用moment.js库:
```javascript
var timestamp = 1612345678; // 时间戳
var formattedDate = moment.unix(timestamp).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate); // 输出:2021-02-03 12:34:38
```