CodeBlanks Logo Icon CodeBlanks

Date methods

Learn getDate, getMonth and getFullYear methods.

Date methods

You access a Date object's components with methods. getFullYear() returns the four-digit year; getMonth() the month as a zero-based number (January=0, December=11); getDate() the day of the month.

Example: for new Date("2024-03-15"), getFullYear() returns 2024, getMonth() returns 2 (March), getDate() returns 15. For time there are getHours(), getMinutes(), getSeconds(). These methods work in the local timezone; for UTC use getUTCFullYear(), getUTCMonth(), getUTCDate(). For deterministic test output prefer the UTC methods. getDay() returns the day of the week (Sunday=0).

UTC methods

Local methods depend on the machine's timezone; they give different results in different countries. UTC methods (getUTCFullYear, getUTCMonth, getUTCDate) give the same result everywhere.

Example: for new Date("2024-03-15T00:00:00Z"), getUTCDate() is always 15. getDate() may be 15 in Istanbul (+3) but 14 in New York (-5). This is why test code uses UTC methods. Since the month is zero-based, you usually add 1 when displaying: getUTCMonth() + 1. Date formatting is the topic of the next lesson with Intl.DateTimeFormat; here we only pull components.

Practice Combine date components

Define const date = new Date("2024-03-15T00:00:00Z");. Print in day.month.year format with console.log(date.getUTCDate() + "." + (date.getUTCMonth() + 1) + "." + date.getUTCFullYear()).

Starter code

index.js
// Define a UTC date
// write here

// Print in day.month.year format
// write here

Sample solution

index.js
const date = new Date("2024-03-15T00:00:00:00Z");
console.log(date.getUTCDate() + "." + (date.getUTCMonth() + 1) + "." + date.getUTCFullYear());

Expected output

15.3.2024

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the getFullYear call

Question
const yil = date.____();
Answer
const yil = date.getFullYear();

Explanation: getFullYear returns the four-digit year.

2 Match each method to its returned value

Term Meaning
getUTCFullYear Year (2024)
getUTCMonth Month (March=2)
getUTCDate Day of month (15)
getUTCDay Day of week

3 What does new Date("2024-03-15T00:00:00Z").getUTCMonth() return?

index.js
new Date("2024-03-15T00:00:00Z").getUTCMonth()
  • 0
  • 3
  • 2 Correct answer
  • 15

Explanation: March returns 2 because months are zero-based.

All lessons in Intermediate