First of all, we will create a new object of Date() and declare a variable named “current” and assign the new Object of Date() to a “current” variable.
After assigning, let’s have a look at the object Date what does it have for us.
Alright! It looks pretty cool in a good format. But, how about if we want to get only the year from the entire date? We can use the built-in function getFullYear() for getting the year only.
Similarly, if we want to extract only the year, we can use the built-in function getMonths() for getting the month only.
There seems like an issue. This is not the 8th month(August)! As we can see in the above complete output for the new Date object. This is September. Well, this is because of the digital(0-11). So, we have to add “1” to it for getting the right month every time.
This is fine now.
Just like for the year, we can do the same for the date. For example, to extract or get only the date, we can use the built-in function getDate().
Just like a date, we have built-in functions for extracting the desired piece of time. For example, if we want to get or extract the hours only, from the whole current time, we can use the built-in function getHours().
The same goes for the minutes. To extract minutes only, we can use getMinutes().
To extract seconds only, we can use getSeconds().
Advanced built-in functions
Here we have some advanced built-in functions to get the date and time in a pretty clean and good formatted string. For example, in order to get only the time, not the date, in the form of string we can use the built-in function toLocaleTimeString() to our purpose.
current.toLocaleTimeString(); // “2:42:07 PM”
And, if we want to extract only the time in the form of string. We can use the built-in function toLocaleDateString().
current.toLocaleDateString(); // “9/29/2020”
And, if we want to extract both the date and time in a single string, we can use the built-in function toLocaleString().
current.toLocaleString(); // “9/29/2020, 2:42:07 PM”
So, this is how we can get the date and time using the built-in date object and extract the required months, years, or minutes using different methods.