JavaScript Date Get and Set Methods

JavaScript Date Get and Set Methods

·

3 min read

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
getFullYearGet full year (yyyy)d.getFullYear()
getMonthGet month (0 - 11)d.getMonth()
getDateGet date (1 - 31)d.getDate()
getHoursGet hours (0 - 23)d.getHours()
getMinutesGet minutes (0 - 59)d.getMinutes()
getSecondsGet seconds (0 - 59)d.getSeconds()
getMillisecondsGet milliseconds (0 - 999)d.getMilliseconds()
getTimeGet time (>= 1613560292960)d.getTime()
getDayGet day (0-6)d.getDay()
Date.nowGet 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()];

See another example below:

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

days[d.getDay()];

Parse

The parse method allows you to parse a data string format to get the timestamp in milliseconds from 1 January 1970 till the time specified in the string format.

The syntax is shown below:

Date.parse(str)

See the example below:

const parseTime = Date.parse('2055-01-22T10:48:13.201-06:00');

console.log(parseTime); // 2684249293201

image.png


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
setFullYearSet full year (yyyy)d.setFullYear(...)
setMonthSet month (0 - 11)d.setMonth(...)
setDateSet date (1 - 31)d.setDate(...)
setHoursSet hours (0 - 23)d.setHours(...)
setMinutesSet minutes (0 - 59)d.setMinutes(...)
setSecondsSet seconds (0 - 59)d.setSeconds(...)
setMillisecondsSet milliseconds (0 - 999)d.setMilliseconds(...)
setTimeSet time (>= 1613560292960)d.setTime(...)
setDaySet 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