Time related functions

This page shows how to use number of time-related methods available in JavaScript. We use the methods to get the current year, month, date, day of the week, hour, minutes, and seconds.

The following shows the output of the script code shown below:

Scripting code

Step 1: place the following code in the head section (between <head> and </head>) of your web document.

<script language="javascript">
<!--
function DateAndTimeFunctions () {
var dateObj = new Date();
var strOut;
// get year and that value to a variable called strOut
strOut = "Year: " + dateObj.getFullYear();
// call the CurrentMonth () function; it will return the name of the month
strOut = strOut + "<br>Month: " + CurrentMonth ();
strOut = strOut + "<br>Day of the month: " + dateObj.getDate();
strOut = strOut + "<br>Day of the week: " + GetDayName();
strOut = strOut + "<br>Hour of the day (0 - 23): " + dateObj.getHours();
strOut = strOut + "<br>Minutes (0 - 59): " + dateObj.getMinutes();
strOut = strOut + "<br>Seconds (0 - 59): " + dateObj.getSeconds();
return strOut;
}
function CurrentMonth () {
var dateObj = new Date();
// declare an array
var monthsArr = new Array();
// get the current month; getMonth () returns 0 through 11
var currMonth = dateObj.getMonth();
// fill the array with the names of the months
monthsArr[0] = "January";
monthsArr[1] = "February";
monthsArr[2] = "March";
monthsArr[3] = "April";
monthsArr[4] = "May";
monthsArr[5] = "June";
monthsArr[6] = "July";
monthsArr[7] = "August";
monthsArr[8] = "September";
monthsArr[9] = "October";
monthsArr[10] = "November";
monthsArr[11] = "December";
// return the array index of the current month
return monthsArr[currMonth];
}
function GetDayName () {
var dateObj = new Date();
// create an array
var weekDaysArr = new Array();
// get the current day; getDay () returns 0 through 6
var currDay = dateObj.getDay();
weekDaysArr[0] = "Sunday";
weekDaysArr[1] = "Monday";
weekDaysArr[2] = "Tuesday";
weekDaysArr[3] = "Wednesday";
weekDaysArr[4] = "Thursday";
weekDaysArr[5] = "Friday";
weekDaysArr[6] = "Saturday";
// return current day
return weekDaysArr[currDay];
}
//-->
</script>

Step 2: Call the GetDayName () function from your web page:

<script language="javascript" type="text/javascript">
<!--
document.write (DateAndTimeFunctions ());
//-->
</script>