How to get the current date and time in js

下次还敢
Release: 2024-05-06 09:21:16
Original
497 people have browsed it

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:

const now = new Date(); const date = now.getDate(); console.log(date); // 输出当前日期
Copy after login

Get the current time:

const now = new Date(); const hours = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds(); console.log(`${hours}:${minutes}:${seconds}`); // 输出当前时间
Copy after login

Get the current timestamp:

const timestamp = Date.now(); console.log(timestamp); // 输出当前时间戳
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!