How to Get the Current Date in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the new Date()
Syntax
You can simply use the Date object's toLocaleDateString()
method to get the current date in the desired format in JavaScript. This method is supported in all major modern web browsers.
Let's take a look at the following example to understand how it basically works:
Example
Try this code »// Create a date object
var today = new Date();
// Generate current date string in UK date format (day-month-year)
var ukDate = today.toLocaleDateString("en-GB", {
year: "numeric",
month: "2-digit",
day: "2-digit",
});
console.log(ukDate);
// Generate current date string in US date format (month-day-year)
var usDate = today.toLocaleDateString("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit",
});
console.log(usDate);
To specify options but use the browser's default locale, you can use "default"
instead of "en-US", "en-GB", etc. Possible values for month property are "numeric"
, "2-digit"
, "narrow"
, "short"
, "long"
. While, possible values for year and day properties are "numeric"
, and "2-digit"
.
You can alternatively use the Date object's getDate()
, getMonth()
, and getFullYear()
methods to get the current date and format it according to your need. Let's checkout an example:
Example
Try this code »// Create a date object
var today = new Date()
var year = today.getFullYear();
/* Add 1 to the returned month number, as count for months starts
at 0 (January) and ends at 11 (December). Also place 0 before
single digit month and day number with padStart() method */
var month = String(today.getMonth() + 1).padStart(2, '0');
var day = String(today.getDate()).padStart(2, '0');
// Generate current date string in UK date format (day-month-year)
var ukDate = [day, month, year].join('/');
console.log(ukDate);
// Generate current date string in US date format (month-day-year)
var usDate = [month, day, year].join('/');
console.log(usDate);
Related FAQ
Here are some more FAQ related to this topic: