Q:

How to Get the Current Date in JavaScript

0

How to Get the Current Date in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

// 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:

// 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);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Convert a String to Boolean in JavaScript... >>
<< How to Get the Last Item in an Array in JavaScript...