Home >Web Front-end >JS Tutorial >How Can I Get and Format the Current Date in JavaScript?

How Can I Get and Format the Current Date in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 14:53:10138browse

How Can I Get and Format the Current Date in JavaScript?

Getting the Current Date in JavaScript

In JavaScript, you can retrieve the current date and time using the new Date() constructor. This constructor creates a new Date object initialized with the current date and time.

Getting the Date String

To format the current date as a string, you can use the following steps:

  1. Get the individual date components using the getDate(), getMonth(), and getFullYear() methods from the Date object.
  2. Pad the day and month values with zeros to ensure consistent formatting.
  3. Concatenate the formatted components into a string.

Example Code

The following JavaScript code demonstrates how to get the current date as a formatted string:

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
document.write(today);

This code will output the current date in the following format: mm/dd/yyyy. For example, if the current date is March 8, 2023, the output would be "03/08/2023".

The above is the detailed content of How Can I Get and Format the Current Date in JavaScript?. 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