JavaScript provides an easy way for getting current day and time. For this you just need to create an object Date() by using the function new and assign a reference to this object to a variable. For example,
sets up the variable today with current date and time. The current date and time is taken from the hardware settings of your computer.
The time is stored as the number of milliseconds since 6pm, on December 31, 1969. In order to convert this number into current date/time, you can use the methods shown below. Note that the returned value for January is 0, so you need to add 1 to it to get the actual month number.
Using these functions it is easy to implement automatic setting of the current date in your Web page. The date will be recomputed every time the Web page is loaded.
To achieve this just add the following code to the appropriate place in your Web page:
JavaScript code | Comments |
---|---|
<script type="text/javascript"> var ddd = new Date(); var month = ddd.getMonth()+1; document.write("<b>Today's date: " + month + "/" + ddd.getDate() + "/" + ddd.getFullYear() + "</b>"); </script> |
opening JavaScript creating the Data object ddd retriving the actual month write "Today's date" in bold add month/day add /year and close writing close JavaScript |
You can create not just the current time object, but also a time object corresponding to the number of milliseconds passed since the epoh day above. Use the following format:
sets up the variable today with date and time corresponding to the value of msec. Beware that the date/time created this way will depend on the time zone where your computer is located.
Similarly one can create the time objects corresponding to a specific date and time by passing the following parameter combinations to its constructor: