In JavaScript, the Date object provides methods for both getting and setting various components of a date, such as the year, month, day, hour, minute, second, and millisecond. Understanding these methods is essential for working with dates effectively in JavaScript. In this chapter, we'll explore in detail how to retrieve and modify date components using the Date object's methods.
JavaScript provides methods to retrieve different components of a date.
a. getFullYear(): Returns the year (four digits) of the specified date according to local time.
const currentDate = new Date();
const year = currentDate.getFullYear();
console.log(year); // Output: Current year (e.g., 2024)
b. getMonth(): Returns the month (0-11) of the specified date according to local time.
const currentDate = new Date();
const month = currentDate.getMonth();
console.log(month); // Output: Current month (e.g., 2 for March)
c. getDate(): Returns the day of the month (1-31) of the specified date according to local time.
const currentDate = new Date();
const day = currentDate.getDate();
console.log(day); // Output: Current day of the month (e.g., 31)
d. getHours(), getMinutes(), getSeconds(), getMilliseconds(): Returns the hour, minute, second, and millisecond of the specified date according to local time.
const currentDate = new Date();
const hours = currentDate.getHours();
const minutes = currentDate.getMinutes();
const seconds = currentDate.getSeconds();
const milliseconds = currentDate.getMilliseconds();
console.log(hours, minutes, seconds, milliseconds); // Output: Current time components
JavaScript also provides methods to set different components of a date.
a. setFullYear(), setMonth(), setDate(): Allows you to set the year, month, and day of the month of a date object.
const currentDate = new Date();
currentDate.setFullYear(2025);
currentDate.setMonth(5); // Note: Month is zero-based, so 5 represents June
currentDate.setDate(15);
console.log(currentDate); // Output: Updated date object
b. setHours(), setMinutes(), setSeconds(), setMilliseconds(): Allows you to set the hour, minute, second, and millisecond of a date object.
const currentDate = new Date();
currentDate.setHours(10);
currentDate.setMinutes(30);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);
console.log(currentDate); // Output: Updated date object
Understanding how to get and set date components is essential for working with dates in JavaScript. By mastering the methods provided by the Date object, you'll be able to manipulate dates effectively in your JavaScript applications. Experiment with different date components and explore additional functionalities provided by the Date object to enhance your date manipulation skills. With practice and experimentation, you'll become proficient in handling dates in JavaScript. Happy coding !❤️