Setting a date with Date methods

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Setting a date with Date methods

Date gives you several methods to set dates and time.

Methods to set Date

  1. setFullYear: Set 4 digit year in Local Time
  2. setMonth: Set month of the year in Local Time
  3. setDate: Set day of the month in Local Time

Note: Each method has its UTC equivalent:

  1. setUTCFullYear: Set 4 digit year in UTC
  2. setUTCMonth: Set month of the year in UTC
  3. setUTCDate: Set day of the month in UTC

Methods to set time

  1. setHours: Set hours in Local Time
  2. setMinutes: Set minutes in Local Time
  3. setSeconds: Set seconds in Local Time
  4. setMilliseconds: Set milliseconds in Local Time
  5. setTime: Sets timestamp

Note: Each method (except setTime) has its equivalent too:

  1. setUTCHours: Set hours in UTC
  2. setUTCMinutes: Set minutes in UTC
  3. setUTCSeconds: Set seconds in UTC
  4. setMilliseconds: Set milliseconds in UTC

Using the set methods

You can use any method here to change a date. Here’s an example where we change the month from November to December.

const date = new Date(2019, 10)
console.log(date) // 01 Nov 2019

date.setMonth(11)
console.log(date) // 01 Dec 2019

Exercise

Create a Date object and set it to 23 June 2019 at 8pm Local Time.

Do the following:

  1. Set minutes to 59
  2. Set hours to 22
  3. Set date to 15

console.log the new date at each point. What’s this new date. Can you explain why you get that result?