HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Date Set Methods

Date set methods allow you to change the value of an existing Date object. You can set specific components like the year, month, day, or even milliseconds.


Essential Set Methods

Method Description
setFullYear() Sets the year (optionally month and day)
setMonth() Sets the month (0-11)
setDate() Sets the day of the month (1-31)
setHours() Sets the hour (0-23)
setTime() Sets the time (ms since Jan 1, 1970)

Date Arithmetic: Adding Days

You can easily add days to a date by combining setDate() and getDate(). JavaScript will automatically handle the overflow into new months or years.

const d = new Date();
// Add 50 days to the current date
d.setDate(d.getDate() + 50); 

Comparing Dates

Dates can be compared using comparison operators (>, <, >=, <=). This works because JavaScript converts the dates into their numeric millisecond values for the comparison.

let today = new Date();
let someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {
  text = "Today is before January 14, 2100.";
} else {
  text = "Today is after January 14, 2100.";
}
Logic Note: Note that == or === will not work to compare if two dates are the same moment. You must compare their getTime() values instead.

Key Points to Remember

  • Set methods permanently modify the Date object's internal value
  • setFullYear() can also take month and day as optional parameters
  • JavaScript handles overflow (e.g., setting the day to 32 will move it to the 1st of the next month)
  • Use the "Get + Offset" pattern for date calculations
  • Compare dates using getTime() for identical equality checks
  • All set methods return the new time as milliseconds