js时间戳转时间格式
时间: 2023-08-18 11:14:59 浏览: 72
可以使用JavaScript内置的`Date()`对象来将时间戳转换为可读的时间格式。具体步骤如下:
1. 创建一个`Date`对象,将时间戳作为参数传入:
```javascript
let timestamp = 1624342436000;
let date = new Date(timestamp);
```
2. 使用`getFullYear()`、`getMonth()`、`getDate()`、`getHours()`、`getMinutes()`、`getSeconds()`方法分别获取年、月、日、小时、分钟、秒:
```javascript
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
```
3. 将获取到的年月日时分秒拼接成需要的时间格式:
```javascript
let time = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
```
完整代码示例:
```javascript
let timestamp = 1624342436000;
let date = new Date(timestamp);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
let time = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
console.log(time);
```
输出结果:`2021-6-22 15:33:56`
阅读全文