Working with JavaScript Date() Object

Date() object in JS is really helpful when working with date and time in your JS code. Whenever we create a date object in JS, we get a timestamp of the current time calculated from the 1 JAN 1970 UTC time zone.

Constructor

When calling the date as new Date():

new Date()

the constructor gets invoked and an object is returned which has the current date and time in format:

image.png

Methods

  • Date.now()

Returns the number of seconds elapsed since 1st JAN 1970 UTC. This method is a lot helpful while assigning timestamps in your code.

image.png

  • getDay()

Returns the number of the day of the week where the week starts from Sunday [0] and ends at Saturday [6]. Returns an integer [0-6].

image.png

  • getDate()

Return the day of the current month, starting from 1 to 31 [depending on the number of days in the month]

image.png

- getMonth()

Returns the month of the year in a integer format, where January is 0 and December is 11. Always remember to add +1 to your month as the months in JS are starting from 0.

image.png

  • getFullYear()

Returns the current year in format 'YYYY'.

image.png

  • getHour()

Returns the current hours in Integer format. The range is from 0 to 23, where 0 means 12 AM and 23 means 11 PM.

image.png

  • getMinutes()

Returns the minute passed in the current hour. The range is from 0 to 59 mins.

image.png

  • getSeconds()

Returns the seconds passed in the current minute in a integer format ranging from 0 to 59 seconds.

image.png

One more important method to add up days in a date() object is:

  • setDate()

This sets the current date of the object to the specified date in the brackets. But this methods is often helpful for manipulation of the date in JS, by adding and substracting the days from the date() object.

In the below example, the current date is 25th AUG and by the use of setDate() methods we will add up 5 days to the current date.

image.png

Similarly, there are some other methods that might come handy when working with date() object in your code, do read more about it:

  1. setFullYear()
  2. setTime()
  3. setUTCDate()
  4. toDateString()
  5. toISOString()
  6. toJSON()
  7. toLocaleString()