📜  node js unix 时间戳 - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:53.585000             🧑  作者: Mango

Node.js Unix 时间戳 - JavaScript

在 Node.js 中,可以通过内置的 Date 对象的方法来获取 Unix 时间戳。

什么是 Unix 时间戳?

Unix 时间戳是一个表示时间的数字,它是从 1970 年 1 月 1 日 00:00:00 UTC 开始经过的秒数。Unix 时间戳通常用于计算机系统中,以表示某个时间点的精确时间。

获取 Unix 时间戳

要获取当前的 Unix 时间戳,可以使用 Date.now() 方法。

const unixTimestamp = Date.now(); // 返回当前时间的 Unix 时间戳
console.log(unixTimestamp);

该代码片段将输出当前时间的 Unix 时间戳。

```javascript
const unixTimestamp = Date.now(); // 返回当前时间的 Unix 时间戳
console.log(unixTimestamp);

要获取指定日期时间的 Unix 时间戳,可以使用 `Date.parse()` 方法。

```javascript
const unixTimestamp = Date.parse('2021-08-01T12:00:00.000Z') / 1000; // 返回 1627819200
console.log(unixTimestamp);

该代码片段将输出 2021-08-01T12:00:00.000Z 的 Unix 时间戳。

将 Unix 时间戳转换为日期时间

要将 Unix 时间戳转换为日期时间,可以使用 Date 对象的构造函数和相关方法。

const unixTimestamp = 1627819200;
const date = new Date(unixTimestamp * 1000);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
console.log(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);

该代码片段将输出 2021-08-02 12:00:00,这是 Unix 时间戳 1627819200 对应的日期时间。

总结

使用 Node.js 的 Date 对象,可以轻松地获取 Unix 时间戳和将其转换为日期时间。Unix 时间戳在计算机系统中被广泛使用,它是表达时间的一种简便方法。