JS Date Get Methods 📝🎯

beginner
13 min

JS Date Get Methods 📝🎯

Welcome to another enlightening journey with CodeYourCraft! Today, we're diving into the fascinating world of JavaScript Date Get Methods. These methods allow us to work with dates and times in our JavaScript projects. Let's get started!

Understanding the Date Object 📝

Before we dive into the get methods, let's quickly create a Date object.

javascript
let currentDate = new Date(); console.log(currentDate);

This line creates a Date object with the current date and time.

Essential Date Get Methods 🎯

Now that we have our Date object, let's explore some essential get methods.

1. getFullYear() 📝

This method returns the year as a 4-digit number.

javascript
let year = currentDate.getFullYear(); console.log(year);

2. getMonth() 📝

This method returns the month (0-11) where January is 0 and December is 11.

javascript
let month = currentDate.getMonth(); console.log(month);

3. getDate() 📝

This method returns the date of the month (1-31).

javascript
let date = currentDate.getDate(); console.log(date);

4. getDay() 📝

This method returns the day of the week (0-6) where Sunday is 0 and Saturday is 6.

javascript
let day = currentDate.getDay(); console.log(day);

5. getHours() 📝

This method returns the hour (0-23) in the day.

javascript
let hours = currentDate.getHours(); console.log(hours);

6. getMinutes() 📝

This method returns the minutes (0-59).

javascript
let minutes = currentDate.getMinutes(); console.log(minutes);

7. getSeconds() 📝

This method returns the seconds (0-59).

javascript
let seconds = currentDate.getSeconds(); console.log(seconds);

Practical Application 🎯

Let's create a simple function that formats a date for a blog post.

javascript
function formatDate(date) { let day = date.getDate(); let month = date.getMonth() + 1; // Months are 0-11 let year = date.getFullYear(); return `${day}/${month}/${year}`; } let blogPostDate = new Date(); let formattedDate = formatDate(blogPostDate); console.log(formattedDate);

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What method returns the year as a 4-digit number?

Quick Quiz
Question 1 of 1

Which method returns the day of the week (0-6) where Sunday is 0 and Saturday is 6?