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

How to get the current date in js

下次还敢
Release: 2024-05-01 07:06:15
Original
690 people have browsed it

To get the current date in JavaScript, you can use the following methods: Date.now() Returns the number of milliseconds that have elapsed since January 1, 1970. new Date() returns a Date object representing the current moment. The following methods can be used to obtain the date component: getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(). You can use the following methods to format dates: toLocaleDateString(), toLocaleTimeString(), toISOSt

How to get the current date in js

##How to get the current date in JavaScript

In JavaScript, you can get the current date through the following methods:

1. Date.now()

Date.now() Returns the number of milliseconds elapsed from midnight on January 1, 1970 to the current moment. You can get the date object using the following method:

<code class="js">const date = new Date(Date.now());</code>
Copy after login

2. new Date()

new Date() Returns a date representing the current moment Date object. You can get the date object in the following ways:

<code class="js">const date = new Date();</code>
Copy after login

Get the date components

Get the components of the date object (such as year, month, day, hour, minute, second) , you can use the following methods:

  • getFullYear(): Get the year
  • getMonth(): Get the month (0-11)
  • getDate(): Get the date (1-31)
  • getHours(): Get the hour (0-23)
  • getMinutes(): Get minutes (0-59)
  • getSeconds(): Get seconds (0-59)
For example, to get the current year:

<code class="js">const year = date.getFullYear();</code>
Copy after login

Format date

To format the date, you can use the following method:

  • toLocaleDateString(): Returns a localized date string
  • toLocaleTimeString(): Returns a localized time string
  • toISOString(): Returns an ISO 8601 date string
For example, to get the localized date string:

<code class="js">const formattedDate = date.toLocaleDateString();</code>
Copy after login

The above is the detailed content of How to get the current date 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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template