Tuesday, March 8, 2016

Simple JavaScript code - Hello World and Current Time

Here is a simple JavaScript code for beginners:

<script language="JavaScript">
<!--
//Hello, World and Random Number
document.write("Hello, JavaScript!");
var myRand = Math.round(Math.random()*100);
var myStr1 = "<br><br>My Random number between 0 and 100:  <b><font size=+2 color=red>"
var myStr2 = "</font></b><br><br>"
document.write(myStr1+myRand+myStr2);

//Date and Time
var month_array = new Array("January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December");
var weekday_array = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

var nowDate = new Date();
var year = nowDate.getFullYear();
var month = nowDate.getMonth();
var day = nowDate.getDate();
var weekday = nowDate.getDay();
var hour = nowDate.getHours();
var ampmStr = hour > 12 ? " PM" : " AM";
hour %= 12;
var minute = nowDate.getMinutes();
var second = nowDate.getSeconds();

//Add 0 if only one digit. See: http://stackoverflow.com/questions/8513032/less-than-10-add-0-to-number
hour = ('0' + hour).slice(-2)
minute = ('0' + minute).slice(-2)
second = ('0' + second).slice(-2)

document.write("Now is:<br>");
document.write(hour+":"+minute+":"+second+ampmStr+"<br>")
document.write(weekday_array[0]+"<br>"+month_array[month]+" "+day+", "+year+"<br><br>")


//Simple Calculation
var a = 3;
var b = 4;
var sum = a+b;
document.write(a+" + "+b+" = "+sum)
</script>
<noscript>
Your browser doesn't support JavaScript.
</noscript>

Result:



Related Information:

JavaScript and JSON

No comments:

Post a Comment