How to get the Current date in Javascript?

Date Object in Javascript

Javascript provides the Date() object to get the Current date & time. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. The Date methods can be used to get the required Date or Time information from that object.The Date object is created by using new keyword, i.e. new Date().

Syntax to create a Date object

The Date() constructor creates a date object which sets the current time and date details based on the browser’s time zone.

Example

Output

Get the Current date from Date object in Javascript

The below date methods are used to get the date,month and year from the date object.

  • getFullYear() – Get a year of four digit number (yyyy)
  • getMonth() – Get a month as a number (0-11). 0 represents January & 1 represents February and so on.
  • getDate() – Get a day as a number (1 – 31)

Example :

Output

As we run this code on May 1st,2020, We got the year as 2020, month as 5 and day as 1.

Get Month and Date in two digit format using Javascript

The getmonth() and getdate() function returns the single digit for the month/day if the number is lesser than 10. Lets see how to get the month and date in two digit format (mm/dd). Assume that we run this code on 1st,May,2020. So the date object is returning the below values for the date methods.

MethodReturn value (as per the below code)
today.getFullYear()2020
today.getMonth()4
today.getDate()1

Both getMonth() and getDate() functions returns a single digit. So we are validating the month/day number using if condition and concatenating the digit 0 before the month/day number

Example

Output

Get the current date in Javascript
Get the current date in Javascript