AlfieWebDevTips Homefor new and experienced developers
[Home Home] [Web Development Web Development ] [Code Generators Code Generators ] [Resources Resources ] [Contact Us Contact ] |WebDevTips Privacy Privacy |
Print This Page

You are here : Home - Web Development - Javascript - Date and Time

Date and Time



Putting the date and time on your page with javascript is fairly simple. Javascript provides useful ways of getting the individual elements of the date and time.

new Date();
getYear();
getMonth();
getDay();
getDate();
getHours();
getMinutes();
getSeconds();

getMonth(); and getDay(); return the values as numbers so all we have to is create a name array so we can use names.

Here's what the result of the script below looks like

Heres the code

<script language="javascript" type="text/javascript"> 
<!-- 
var myDate=new Date(); 
var myYear = myDate.getYear(); 
var myMonth = myDate.getMonth(); 
var myDay = myDate.getDay(); 
var myDayNo = myDate.getDate(); 
var myHrs = myDate.getHours(); 
var myMin = myDate.getMinutes(); 
var mySec = myDate.getSeconds(); 
 
var MonthName = new Array(12); 
MonthName[1] ="January"; 
MonthName[2] ="February"; 
MonthName[3] ="March"; 
MonthName[4] ="April"; 
MonthName[5] ="May"; 
MonthName[6] ="June"; 
MonthName[7] ="July"; 
MonthName[8] ="August"; 
MonthName[9] ="September"; 
MonthName[10] ="October"; 
MonthName[11] ="November"; 
MonthName[12] ="December"; 
 
var DayName = new Array(7); 
DayName[1] ="Sunday"; 
DayName[2] ="Monday"; 
DayName[3] ="Tuesday"; 
DayName[4] ="Wednesday"; 
DayName[5] ="Thursday"; 
DayName[6] ="Friday"; 
DayName[7] ="Saturday"; 
 
 
//fix the year for ns4x 
if (myYear<2000){myYear+=1900;} 
 
document.write("<table border='0' align='center'>") 
document.write("<tr><td align='right'><b>Year</b></td><td> " + myYear + "</td></tr>"); 
document.write("<tr><td align='right'><b>Month</b></td><td> " + MonthName[myMonth+1] + "</td></tr>"); 
document.write("<tr><td align='right'><b>Day</b></td><td> " + DayName[myDay+1] + "</td></tr>"); 
document.write("<tr><td align='right'><b>Date</b></td><td> " + myDayNo + "</td></tr>"); 
document.write("<tr><td align='right'><b>Hour</b></td><td> " + myHrs + "</td></tr>"); 
document.write("<tr><td align='right'><b>Minute</b></td><td> " + myMin + "</td></tr>"); 
document.write("<tr><td align='right'><b>Second</b></td><td> " + mySec + "</td></tr>"); 
document.write("</table>") // --> 
</script>

You can format all the document.write stuff to display however you want.

Other examples







Google
 

[back to top of page]   

[labelled with icra -  - this link will open in a new window] [RSS Content]

[Copyright © WebDevTips]