Home >Web Front-end >JS Tutorial >How to get the current date and time in js

How to get the current date and time in js

下次还敢
下次还敢Original
2024-05-06 09:21:16628browse

There are two ways to get the current date and time in JavaScript: 1. Use the Date object to create a new Date object, and use this object to get the date, month, year, hour, minute, and second. 2. Use JavaScript built-in functions to get the current timestamp and convert it into a date object.

How to get the current date and time in js

Get the current date and time

How to get the current date and time?

In JavaScript, there are two main ways to get the current date and time:

1. Use the Date object

  • Create a new Date object: const now = new Date();
  • Get the current date and time: now.getDate()(date),now.getMonth() (month), now.getFullYear() (year), now.getHours() (hour), now.getMinutes () (minutes), now.getSeconds() (seconds)

2. Use JavaScript built-in function

  • Get the current timestamp: const timestamp = Date.now();
  • Convert the timestamp to a date object: const date = new Date(timestamp);

Specific example:

Get the current date:

<code class="js">const now = new Date();
const date = now.getDate();
console.log(date); // 输出当前日期</code>

Get the current time:

<code class="js">const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
console.log(`${hours}:${minutes}:${seconds}`); // 输出当前时间</code>

Get the current timestamp:

<code class="js">const timestamp = Date.now();
console.log(timestamp); // 输出当前时间戳</code>

The above is the detailed content of How to get the current date and time in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn