Creating Date Objects
Date objects are created with the new Date() constructor.
There are 4 ways to create a new date object:
1. new Date()
2. new Date(year, month, day, hours, minutes, seconds,
milliseconds)
You cannot omit month. If you supply only one parameter it will be treated
as milliseconds.
const d = new Date(2018);
Thu Jan 01 1970 05:30:02 GMT+0530 (India Standard Time)
3. new Date(milliseconds)
4. new Date(date string)
Note: JavaScript counts months from 0 to 11:
January = 0.
December = 11.
Specifying a month higher than 11, will not result in an error but add the
overflow to the next year:
Example :-
const d = new Date(2018, 15, 24, 10, 33, 30);
Is the same as:
const d = new Date(2019, 3, 24, 10, 33, 30);
Specifying a day higher than max, will not result in an error but add the overflow
to the next month:
Specifying:
const d = new Date(2018, 5, 35, 10, 33, 30);
Is the same as:
const d = new Date(2018, 6, 5, 10, 33, 30);
1) getTime()
The getTime() method returns the number of milliseconds since
January 1, 1970:
2) getMonth()
The getMonth() method returns the month of a date as a number (0-
11):
3) getDate()
The getDate() method returns the day of a date as a number (1-31):
4) getHours()
The getHours() method returns the hours of a date as a number (0-
23):
5) setDate()
The setDate() method sets the day of a date object (1-31):
6) setHours()
The setHours() method sets the hours of a date object (0-23):
7) setMinuites()
The setMinutes() method sets the minutes of a date object (0-59):
Example :-
<!DOCTYPE html>
<html>
<body>
Set date :-
<script>
const d = new Date();
d.setDate(15);
document.write(d);
</script>
</body>
</html>