Table of Contents
- Date object
- Get Current Year
- Get Current Month
- Get Current Time and Date
- Other Related Concepts
We could create a date object in four different ways
new Date() new Date(year, month, day, hours, minutes, seconds, milliseconds) new Date(milliseconds) new Date(date string)
new Date() new Date() creates a new date object with the current date and time:
var d = new Date();
new Date(year, month, ...) new Date(year, month, ...) creates a new date object with a specified date and time.
7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
var d = new Date(2021, 03, 16, 17, 55, 44, 0);
new Date(milliseconds) creates a new date object as zero time plus milliseconds:
var d = new Date(0);
One thing to keep in mind about the date object is that it is a static object.
Now that we have looked at the different methods of creating a date object, we shall use the first method and get the specific details we need.
Get Current YeargetFullYear() method can be used to get current year from the current date object
var d = new Date(); var year = d.getFullYear(); console.log(year); //Output: 2021
Get Current Month:Similar to the year, we can also get the current month using the getMonth() method.
var d = new Date(); var month = d.getMonth(); console.log(month); //Output: 3
As mentioned before, the months are calculated from 0 to 11 instead of 1 to 12. To get an output in a readable format, we could just add 1 to the output.
Get Current Date:The getDate() method can be used to get the day of the month.
var d = new Date(); var day = d.getDate(); console.log(day); //Output: 16
Get current Time and DateSimilarly, we can use the following methods to get current time in seconds, minutes, and hours separately and also together.
var d = new Date(); var hr = d.getHours();console.log(hr); var min = d.getMinutes();console.log(min); var sec = d.getSeconds();console.log(sec); var time = d.toLocaleTimeString();console.log(time); var date = d.toLocaleDateString();console.log(date); var datetime = d.toLocaleString();console.log(datetime); //Output: 12 44 24 12:44:24 PM 4/16/2021 4/16/2021, 12:44:24 PM