The native Date object in Javascript enables the date and time related actions in Javascript. The values inline with the UNIX epoch, meaning that it is based on the the number of milliseconds elapsed after 1970.01.01 0000 hrs UTC. However since the Javascript code is executed in the local web browser, the values are related to the local time of the computer where the code gets executed.
The object has following constructors:
Date( ) – creates a date object with current date and time values.
Date(Year, Month, Date, Hour, Minutes, Seconds, Milliseconds) – creates a date object with the specified values
Note month starts from 0, January is 0 while December is 11 and all the parameter of the constructor are optional.
Check the following examples:
let datenTime = new Date(); console.log("Current Time : " + datenTime); let passedDatenTime = new Date(1990, 3, 28, 0, 0, 1, 30); console.log("Passed Time : " + passedDatenTime); let futureDatenTime = new Date(2024, 5, 2, 12, 30); console.log("Future Time : " + futureDatenTime);
Output
Current Time : Tue Apr 28 2020 08:24:32 GMT+0530 (India Standard Time)
Passed Time : Sat Apr 28 1990 00:00:01 GMT+0530 (India Standard Time)
Future Time : Sun Jun 02 2024 12:30:00 GMT+0530 (India Standard Time)
Once the object is created, the parameters can be extracted using the following methods.
let datenTime = new Date(); console.log("Current Year : " + datenTime.getFullYear()); console.log("Current Month : " + datenTime.getMonth()); console.log("Current Date : " + datenTime.getDate()); console.log("Current Hour : " + datenTime.getHours()); console.log("Current Minute : " + datenTime.getMinutes()); console.log("Current Seconds : " + datenTime.getSeconds()); console.log("Current Millisecond : " + datenTime.getMilliseconds());
Output
Current Year : 2020
Current Month : 3
Current Date : 28
Current Hour : 8
Current Minute : 30
Current Seconds : 37
Current Millisecond : 809
Note that the current month value is 3, because it starts with 0. Therefore 3 means April.
Another important method is .getTime( ) which returns number of milliseconds from 1970.01.01 0000 hrs UTC. It is useful to calculate duration. For example, following illustrates calculating time taken to execute a code fragment.
timeConsumingJob(); async function timeConsumingJob() { let start_time = new Date(); await sleep(2000); let end_time = new Date(); let duration = end_time.getTime() - start_time.getTime(); console.log("Duration = " + duration); } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }