📅  最后修改于: 2023-12-03 14:50:57.472000             🧑  作者: Mango
在 JavaScript 中,有许多方法可以获取时间,这些方法可以帮助我们开发一些更高级的应用程序。下面是一些方法:
JavaScript 中的 Date 对象可以返回有关日期和时间的信息。可以使用该对象的各种方法和属性,例如 getFullYear
、getMonth
、getDate
、getHours
、getMinutes
、getSeconds
等等,可以获取有关日期和时间的特定部分。以下是使用 Date 对象获取时间的示例代码:
const date = new Date();
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-07-01 12:30:45
。
Date.now()
方法可以返回从 1970 年 1 月 1 日 00:00:00(UTC)到当前时间的毫秒数。以下是使用 Date.now()
获取时间的示例代码:
const timestamp = Date.now();
console.log(timestamp);
上述代码将打印当前时间的时间戳,例如 1625117425358
。
可以通过将一个时间戳(自 1970 年 1 月 1 日 00:00:00 UTC)作为参数传递给 Date
构造函数,创建一个新的 Date
对象。以下是使用 new Date()
获取特定时间的示例代码:
const timestamp = 1625117425358;
const date = new Date(timestamp);
console.log(date);
console.log(date.getFullYear());
console.log(date.getMonth() + 1);
console.log(date.getDate());
console.log(date.getHours());
console.log(date.getMinutes());
console.log(date.getSeconds());
上述代码将打印时间戳所代表的时间,例如:
Thu Jul 01 2021 21:30:25 GMT+0800 (中国标准时间)
2021
7
1
21
30
25
JavaScript 中有很多方法可以获取时间。我们可以使用 Date
对象来获取特定部分的日期和时间。我们还可以使用 Date.now()
来获取当前时间的时间戳,或者使用 new Date(milliseconds)
来获取特定时间的信息。