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.
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
const now = new Date();
now.getDate()
(date),now.getMonth()
(month), now.getFullYear()
(year), now.getHours()
(hour), now.getMinutes ()
(minutes), now.getSeconds()
(seconds) 2. Use JavaScript built-in function
const timestamp = Date.now();
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!