Last Updated : Oct 19, 2023
You will have a thorough understanding of the process to access and modify various elements of the present date by the conclusion of this course.
Getting the current date is a basic job in many online applications.
Having the ability to access the current date is crucial for conducting date-related computations, logging timestamps, and presenting the date to users.
To extract distinct parts of the current date, we will use a variety of Date object methods, and we will then break down each part's relevance step by step.
<script> const cDate = new Date(); const cYear = cDate.getFullYear(); const cMonth = cDate.getMonth() + 1; // Months are 0-based, so add 1 const cDay = cDate.getDate(); console.log("Current Year:", cYear); console.log("Current Month:", cMonth); console.log("Current Day:", cDay); </script>
- Constant variable cDate is given a new instance within the Date object by the line const cDate = new Date();. The time and date are represented by this object.
- The formula is const cYear = cDate.getFullYear(); The current year is retrieved using the getFullYear() function from the Date object in the given line. After that, the value is kept in the cYear constant variable.
- Const cDay = cDate.getDate(); retrieves the day of the month from a Date object using the getDate() function. The cDay constant variable holds the value.
- The current year, month, and day values are printed to the console using the console.log() commands.
- console.log("Current Year:", cYear); prints the value of the current year in addition to it.
- console.log("Current Month:", cMonth); prints the value of the current month in addition to it.
- console.log("Current Day:", cDay); prints the value of the current date in addition to it.
We may quickly retrieve the year, month date of the current date by using the Date object and its related methods.
This information is crucial for a variety of web development duties, including providing users with real-time information, logging timestamps, and carrying out time-based computations.