Home > Article > Web Front-end > How to get the current date and time in js
There are three ways to get the current date and time in JavaScript: use the Date object to provide date and time properties, such as date.getDate(), date.getMonth(), etc. Using the Date.now() method, returns the number of milliseconds since the epoch. Uses an ISO standard format string containing information such as year, month, date, hours, minutes, seconds, and millisecond time zone offset.
In JavaScript, there are the following methods to get the current date and time:
Date
object represents a date and time. A new Date object can be created in the following way:
<code class="js">const date = new Date();</code>
This object contains information about the current date and time, which can be accessed through the following properties:
date.getDate( )
: Returns the date of the current date (1-31) date.getMonth()
: Returns the month of the current date (0-11) date.getFullYear()
: Returns the year of the current date date.getHours()
: Returns the hour of the current time date. getMinutes()
: Returns the minutes of the current timedate.getSeconds()
: Returns the seconds of the current timedate.getMilliseconds()
: Return the milliseconds of the current time Date.now()
method to return the elapsed time since the epoch Number of milliseconds. It can be used in the following ways:
<code class="js">const msSinceEpoch = Date.now();</code>
Date
objects in JavaScript can be converted to ISO 8601 standard format strings. The string contains the following information:
The ISO format string can be obtained using the following syntax:
<code class="js">const isoString = date.toISOString();</code>
Sample code to get the current date and time:
<code class="js">const date = new Date(); const fullDate = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`; const fullTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; console.log(`Current date: ${fullDate}`); console.log(`Current time: ${fullTime}`);</code>
Output:
<code>Current date: 31/12/2023 Current time: 12:00:00</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!