JavaScript provides us with a built-in object named Date to work with time. This object works differently than the global object.
To work with a Date object, we have to call the Date constructor function.
We can work with Date objects in three ways …
- Directly work with a Date constructor function
- With the method of a constructor function
- Work with a date object created with the date constructor function.
Directly work with the Date constructor function:
console.log(typeof Date());// Result: string
With the method of constructor function:
If we print the Date in the console…
console.log(typeof Date);// Result: Function
Date.now():
This method will return the present time with milliseconds from 1st January 1970.
Date.parse():
Date.UTC():
This method will return milliseconds from 1st January 1970. It will take a year, month, day, hour, minute, and second as arguments.
Prototype method:
The prototype method will not work with the constructor function directly. It will work only for the object made with the constructor function.
Work with date object created with date constructor function:
We know if we want to create an object from a constructor function, we need a new keyword.
Now we will create a Date object with a new keyword in front of the Date() constructor function.
Now with the date object, we can access the method of the prototype of the Date object.
We can call the constructor function in different ways …
1. Without passing any argument
-- the new Date() will return to the present time
2. After passing the arguments
-- new Date(year, month, day, hours, minutes, seconds, milliseconds)
-- Here, except for year and month, the remaining options are optional.
N.B ⇒ Month will take the index number from 0 to 11. If we give the number out of the range between 0 to 11, then it will take the next month as for example, 12 is for January.
Example:
For the day, 32 will take the next month.
If we pass milliseconds as an argument of new Date(), then milliseconds will add with the milliseconds of the 1st January 1970.
console.log(new Date(86400000);
The milliseconds 86400000 will add with the milliseconds of the 1st January 1970 is 0.
0 + 86400000 = 86400000 will be transformed into a date object.
Make date object from date string:
We can also make a date object from a date string.
We can now access all the methods of the Date object.
Go to the browser console, and type the following code…
console.dir(new Date());
This will show the following code… click on the triangle sign to open the methods.
When we use the numbers as the arguments to the Date constructor function, then the month and day will count as the index number.
However, when the string is used as the argument to the Date object, then the index number will not be counted, normal number counting will consider.
Post a Comment