Javascript Date setDate(date)

Introduction

Javascript Date setDate(date) sets the day of the month for the date.

dateObj.setDate(dayValue)

dayValue is an integer representing the day of the month.

Return value

The number of milliseconds between 1 January 1970 00:00:00 UTC.

The given date is changed in place.

If the date is greater than the number of days in the month, the month value also gets increased.

For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month.

For a negative dayValue, the date will be set counting backwards from the last day of the previous month.

-1 would result in the date being set to 1 day before the last day of the previous month.

To increase the date '28 Feb 2020'? by 2 days.

let date = new Date(2020, 1, 28);
date.setDate(date.getDate() + 2);// w ww.j  a  v a 2s .  c  o  m

console.log( date ); 

We can set zero or even negative values. For example:

let date = new Date(2016, 0, 2); // 2 Jan 2016

date.setDate(1); // set day 1 of month
console.log( date );/*w  ww .j a  v a  2  s  .co m*/

date.setDate(0); // min day is 1, so it sets to the last day of the previous month
console.log( date ); // 31 Dec 2015

let d = new Date(2020, 6, 7); 
console.log(d);
d.setDate(30);  
console.log(d);
d.setDate(0); 
console.log(d); 
d.setDate(-1);  
console.log(d); 
d.setDate(98); 
console.log(d); 
d.setDate(-50);
console.log(d);

More example,

var d = new Date("July 21, 2010 01:15:00");
d.setDate(15);//from   ww  w. j a  v a  2s.c  o m
console.log(d);
 



PreviousNext

Related