Date and Time in JavaScript
Date object in JavaScript can be used to get date and time. Date object has various methods to exploit date and time. To get date and time use new keyword followed by with Date object constructor.
Syntax
//get date and time new Date(); //set date and time new Date(year, month, date, hours, minutes, seconds, milliseconds);
Example
<script> var now = new Date(); document.write(now); //Fri Feb 20 2015 21:12:09 GMT+0530 (India Standard Time) document.write('<br />'); now = new Date(2005, 11, 21, 12, 30, 30, 0); document.write(now); //Wed Dec 21 2005 12:30:30 GMT+0530 (India Standard Time) </script>
Working with Date
To get and set date, Date objects has various methods.
date.getDay() | returns the day number (0-6, 0 for sun, 1 for mon and so on) |
date.getDate() | returns the date (1 to 31) |
date.getMonth() | returns the month (0-11, 0 for jan and so on) |
date.getFullYear() | returns 4 digit year |
date.setDate(value) | sets the date (1 to 31) |
date.setMonth(value) | sets the month (0-11, 0 for jan and so on) |
date.setFullYear() | sets 4 digit year |
Example
<script> var days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat']; var months = ['Jan', 'Feb', 'March', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var d = new Date(); var day = d.getDay(); day = days[day]; var date = d.getDate(); var month = d.getMonth(); month = months[month]; var year = d.getFullYear(); document.write(day + " " + date + " " + month + " " + year); </script>
Working with Time
To get and set time, Date objects has various methods.
date.getHours() | returns hour in 24-hour format (0-23) |
date.getMinutes() | returns minute (0-59) |
date.getSeconds() | returns second (0-59) |
date.getMilliseconds() | returns millisecond (0-999) |
date.setHours() | sets hour in 24-hour format (0-23) |
date.setMinutes() | sets minute (0-59) |
date.setSeconds() | sets second (0-59) |
date.setMilliseconds() | sets millisecond (0-999) |
Example
<script> var t = new Date(); var hour = t.getHours(); var min = t.getMinutes(); var sec = t.getSeconds(); var milli = t.getMilliseconds(); document.write(hour + ":" + min + ":" + sec + ":" + milli); </script>