- The Date class represents a date and time, accurate
to the nearest millisecond.
- Print the current date and time:
var d = new Date( );
document.writeln(d);
// Output:
Sun Feb 21 2021 10:11:22 GMT-0600 (Central Standard Time)
- Print an arbitrary date. If not specified the time is midnight (00:00:00).
Notice that for the month, 2 represents March, not February, because JavaScript
month indices are zero-based.
var d = new Date(1978, 2, 18);
document.writeln(d);
// Output:
Sat Mar 18 1978 00:00:00 GMT-0600 (Central Standard Time)
- Print an arbitrary date and time. The time is 24-hour time.
var d = new Date(1978, 2, 18, 23, 59, 58);
document.writeln(d);
// Output:
Sat Mar 18 1978 23:59:58 GMT-0600 (Central Standard Time)
- The Date class has methods getYear,
getMonth,
getDay,
getHours, getMinutes,
getSeconds, and getTime.
- The first six of these methods are what you expect:
var d = new Date( );
var yr = d.getFullYear( );
var mon = d.getMonth( );
var day = d.getDate( );
var hr = d.getHours( );
var min = d.getMinutes( );
var sec = d.getSeconds( );
document.writeln(`${yr} ${mon} ${day} ${hr} ${min} ${sec}`);
// Output: 2021 1 21 10 31 56
- The getTime method is surprising. It is the number
of milliseconds since midnight, Jan 1, 1970, which is the start of "Unix Time."
Try it out:
var d = new Date( );
document.writeln(d.getTime( ));
- Try this script. Can you figure out why you don't get 0 for output, since
this is the Unix start date?
var d = new Date(1970,0,1);
document.writeln(d.getTime( ));
// Output: 21600000
Answer: If the timezone were GMT (Greenwich Mean Time), the output would be 0.
However, the time is for Central Standard Time, which is 6 hours before GMT. The
date and time 6 hours before midnight on Jan 1, 1970 is Dec 31, 1969:
var d = new Date(1969, 11, 31, 18, 0, 0);
document.writeln(d.getTime( ));
// Output: 0
- Modify the Clock Example so that it obtains the
current time every second from a JavaScript Date object.
This is more accurate than implementing your own
Clock class.