JS时间戳和时间之间转换
时间: 2023-11-24 08:18:32 浏览: 31
可以使用JavaScript内置的Date对象进行时间戳和时间之间的转换。下面是一些基本的示例代码:
1. 时间戳转换为时间
```javascript
const timestamp = 1612345678901; // 时间戳,单位为毫秒
const date = new Date(timestamp); // 将时间戳转为Date对象
const year = date.getFullYear(); // 获取年份
const month = date.getMonth() + 1; // 获取月份,月份从0开始,需要加1
const day = date.getDate(); // 获取日期
const hour = date.getHours(); // 获取小时
const minute = date.getMinutes(); // 获取分钟
const second = date.getSeconds(); // 获取秒钟
console.log(`${year}-${month}-${day} ${hour}:${minute}:${second}`); // 输出格式化后的时间
```
2. 时间转换为时间戳
```javascript
const dateStr = '2021-02-03 12:34:56'; // 时间字符串
const timestamp = new Date(dateStr).getTime(); // 将时间字符串转为时间戳,单位为毫秒
console.log(timestamp); // 输出时间戳
```
需要注意的是,JavaScript的时间戳是以毫秒为单位的,而有些语言的时间戳是以秒为单位的,需要进行单位转换。