📜  现在几点了 - Javascript (1)

📅  最后修改于: 2023-12-03 14:56:14.655000             🧑  作者: Mango

现在几点了 - Javascript

在JavaScript中,获取当前时间与日期的最简单方式是使用Date对象。

获取当前时间
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

console.log(`现在是 ${hours}:${minutes}:${seconds}`);

以上代码中,我们首先创建了一个新的Date对象,它将包含当前日期和时间。然后,我们可以调用getHours()getMinutes()getSeconds()方法来获取当前时、分、秒数。最后,我们将这些信息格式化输出。

获取当前日期

要获取当前日期,我们可以使用类似的代码:

const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1; // 月份是从0开始的,所以要加1
const day = now.getDate();

console.log(`今天是${year}年${month}月${day}日`);

这段代码会获取当前年、月、日,并将它们格式化输出。

组合时间和日期

如果想要获取当前的日期时间,我们可以将两段代码组合起来:

const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

console.log(`现在是 ${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);

最终结果会像这样输出:

现在是 2021-7-16 23:12:35

以上是获取当前时间与日期的相关介绍。在JavaScript中,Date对象提供了很多用于处理日期和时间的方法。如需查看更多详细信息,请参阅官方文档。