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!
Before we dive into the get methods, let's quickly create a Date object.
let currentDate = new Date();
console.log(currentDate);This line creates a Date object with the current date and time.
Now that we have our Date object, let's explore some essential get methods.
This method returns the year as a 4-digit number.
let year = currentDate.getFullYear();
console.log(year);This method returns the month (0-11) where January is 0 and December is 11.
let month = currentDate.getMonth();
console.log(month);This method returns the date of the month (1-31).
let date = currentDate.getDate();
console.log(date);This method returns the day of the week (0-6) where Sunday is 0 and Saturday is 6.
let day = currentDate.getDay();
console.log(day);This method returns the hour (0-23) in the day.
let hours = currentDate.getHours();
console.log(hours);This method returns the minutes (0-59).
let minutes = currentDate.getMinutes();
console.log(minutes);This method returns the seconds (0-59).
let seconds = currentDate.getSeconds();
console.log(seconds);Let's create a simple function that formats a date for a blog post.
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);What method returns the year as a 4-digit number?
Which method returns the day of the week (0-6) where Sunday is 0 and Saturday is 6?