JavaScript Date Get and Set Methods

Subscribe to my newsletter and never miss my upcoming articles

host.png


Date get methods

To get information from a date object, the get method is required.

let assume const d = new Date().

See the table below:

MethodDescriptionExample
getFullYear()Get full year (yyyy)d.getFullYear()
getMonth()Get month (0 - 11)d.getMonth()
getDate()Get date (1 - 31)d.getDate()
getHours()Get hours (0 - 23)d.getHours()
getMinutes()Get minutes (0 - 59)d.getMinutes()
getSeconds()Get seconds (0 - 59)d.getSeconds()
getMilliseconds()Get milliseconds (0 - 999)d.getMilliseconds()
getTime()Get time (>= 1613560292960)d.getTime()
getDay()Get day (0-6)d.getDay()
Date.now())Get current year day in milliseconds (0-6)Date.now()

getMonth(): 0 is January and 11 is February.

getDay(): 0 is Sunday and 6 is Saturday.

The table may also include the Universal Time Coordinated (UTC) date. For example d.getUTCDay().

See the examples below:

const d = new Date();
const months = [
  "Jan", "Feb", "March", "April", "May", "June", 
  "July", "Aug", "Sep", "Oct", "Nov", "Dec"
  ];
months[d.getMonth()];

image.png


const d = new Date();
const days = ["Sun", "Mon", "Tues", "Thur", "Fri", "Sat"];
days[d.getDay()];

Date set methods

To set information from a date object, the set method is required.

let assume const d = new Date().

See the table below:

MethodDescriptionExample
setFullYear()Set full year (yyyy)d.setFullYear(...)
setMonth()Set month (0 - 11)d.setMonth(...)
setDate()Set date (1 - 31)d.setDate(...)
setHours()Set hours (0 - 23)d.setHours(...)
setMinutes()Set minutes (0 - 59)d.setMinutes(...)
setSeconds()Set seconds (0 - 59)d.setSeconds(...)
setMilliseconds()Set milliseconds (0 - 999)d.setMilliseconds(...)
setTime()Set time (>= 1613560292960)d.setTime(...)
setDay()Set day (0-6)d.setDay(...)

The table may also include the Universal Time Coordinated (UTC) date. For example d.setUTCDay().

See the examples below:

const d = new Date();
d.setFullYear(2069);
d; // 2069-mm-ddThrs:mins:secs.msecsZ

It is optional to include Month and day.

const d = new Date();
d.setFullYear(2069, 03, 20);
d; // 2069-04-20Thrs:mins:secs.msecsZ

Mixed set and get methods

It is possible to use both methods together.

See the example below:

const d = new Date();
d.setDate(d.getDate() + 30);
d;

The addition above is handled automatically by the Date object by shifting months or year.

Happy coding!!!


image.png


Learn on Skillshare

Comments (2)

Catalin Pit's photo

You're killing it with this series, Bello! I like it, and well done!

Bello's photo

Wow! I am pleased the series deserves a 5-star rating. Thanks for the feedback Catalin Pit.