JS如何获取当前时间

Date 对象用于在 JavaScript 中获取当前时间。

以下是如何以“h:i:s”格式获取时间。
我们可以随意更改格式。

let currentDate = new Date();
let time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
console.log(time);
  • getHours() – 提供从 0 到 23 的当前小时。
  • getMinutes() – 提供从 0 到 59 的当前分钟数。
  • getSeconds() – 提供从 0 到 59 的当前秒数。

要在单个变量中组合日期和时间,请运行以下命令:

let current = new Date();
let cDate = current.getFullYear() + '-' + (current.getMonth() + 1) + '-' + current.getDate();
let cTime = current.getHours() + ":" + current.getMinutes() + ":" + current.getSeconds();
let dateTime = cDate + ' ' + cTime;
console.log(dateTime);

JS如何获取当前日期

首先是使用 Date() 函数在 JavaScript 中创建一个对象:

let currentDate = new Date()

然后我们应该使用以下脚本以“m-d-y”格式获取当前日期。
我们可以更改格式。

let currentDate = new Date();
let cDay = currentDate.getDate()
let cMonth = currentDate.getMonth() + 1
let cYear = currentDate.getFullYear()
console.log(cDay);
console.log(cMonth);
console.log(cYear);
  • getDate() – 提供月份值 1-31.
  • getMonth() – 为当前月份提供 0-11 个值(1 月为 0,12 月为 11)。我们应该添加 +1 以获得结果。
  • getFullYear() – 提供当前年份。

这是完整的代码:

let currentDate = new Date();
let cDay = currentDate.getDate();
let cMonth = currentDate.getMonth() + 1;
let cYear = currentDate.getFullYear();
console.log("" + cDay + "/" + cMonth + "/" + cYear + "");

日期和时间

JavaScript 提供了一个内置对象 Date 用于处理与所有日期和时间相关的操作。

我们可以使用它来显示当前日期和时间、创建日历、构建计时器等。

创建 Date 对象时,它允许多种方法对其进行处理。
它们中的大多数将使我们能够获取和设置对象的年、月、日、小时、分钟、秒和毫秒字段。

如何在 JavaScript 中获取当前日期和时间

JavaScript Date 原型对象创建了一个新方法,该方法将返回当前日期和时间。

在这个片段中,我们将解释如何逐步完成任务。

日期:2020-06-02 22:16:20 来源:oir作者:oir