How to Subtract Days from Date in JavaScript

To subtract days from date in JavaScript, you need some methods of the Date object. These methods are the following:

  • setDate()
  • getDate()

The code below modifies the date object and returns the time value of the updated date:

Javascript date object and returns the time value
let d = new Date(); console.log('Today is: ' + d.toLocaleString()); d.setDate(d.getDate() - 3); console.log('3 days ago was: ' + d.toLocaleString());

In the first example you will get the current time, in the second one it will print the date you had 3 days before.

Setting the setDate to 0 will return the last day of the previous month (to have the first day of the current month, you can setDate to 1):

Javascript setDate to -1 will return the last day of the month
let d = new Date(); console.log('Today is: ' + d.toLocaleString()); d.setDate(0); console.log(d.toLocaleString());

Date Object

JavaScript Date objects represent a single instance in time in a platform-independent format. They contain a number that represents milliseconds since January 1, 1970, UTC. The getDate() instance method returns the day of the month for the defined date. The returned value is an integer number between 1 and 31 that represents the day of the month for the specified date based on the local time. The setDate() instance method sets the day of the month to a date object. The returned value is a number which denotes the number of milliseconds between the date object and midnight January 1 1970.