How to Get the Current Date¶
let currentDate = new Date()
Then you should use the following script to get the current date in the “m-d-y” format. You can change the format.
let currentDate = new Date(); let cDay = currentDate.getDate() let cMonth = currentDate.getMonth() + 1 let cYear = currentDate.getFullYear() console.log(cDay); console.log(cMonth); console.log(cYear);
- getDate() – Provides the day of the month values 1-31.
- getMonth() – Provides the current month with 0-11 values (0 for Jan and 11 for Dec). You should add +1 to get result.
- getFullYear() – Provides the current year.
Here’s the full code:
let currentDate = new Date(); let cDay = currentDate.getDate(); let cMonth = currentDate.getMonth() + 1; let cYear = currentDate.getFullYear(); console.log("<b>" + cDay + "/" + cMonth + "/" + cYear + "</b>");
How to Get the Current Time¶
Here is how you can get the time in “h:i:s” format. You can change the format whatever you wish.
let currentDate = new Date(); let time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); console.log(time);
- getHours() – Provides the current hour from 0 to 23.
- getMinutes() – Provides the current minutes from 0 to 59.
- getSeconds() – Provides the current seconds from 0 to 59.
To combine date and time in a single variable run the following:
let current = new Date(); let cDate = current.getFullYear() + '-' + (current.getMonth() + 1) + '-' + current.getDate(); let cTime = current.getHours() + ":" + current.getMinutes() + ":" + current.getSeconds(); let dateTime = cDate + ' ' + cTime; console.log(dateTime);
Date and Time¶
When a Date object is created, it allows a number of methods to work on it. Most of them will enable you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object.