We can display current date and time using JavaScript alert window by linking it to a button click event. We can place this button any where inside a page and display time and date once it is clicked by user. This is a simple script and we will try to develop better applications by learning such small examples.
We will be using built in Date object. We can create instances of this object and use in our script like this
var my_time = new Date()
to display current date and time in alert window
Now this instance we can display by using JavaScript alert window.
alert(my_time);
To display the value we can use simple output command like this
var dt= new Date();
document.write(dt);
The output will be like this Sat Jan 28 2012 10:17:04 GMT+0530 (India Standard Time)
Creating Date object
This is the format to be used
new Date(year, month, day, hours, minutes, seconds, milliseconds);
Example :
var dt= new Date('2014','03','14','10','34','45','1000')
Using button Click
Now this alert we will trigger when a button is clicked by a user. Here is onclick event of a button click.
Here is the complete code for the page with Show Time button.
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function show_now() {
var my_time = new Date();
document.getElementById('display').innerHTML=my_time
}
</script>
</head>
<body>
<input type=button value="Show Time" onclick="show_now();">
<div id=display></div>
</body>
</html>
<script type="text/javascript">
function show_date() {
var in_date = new Date();
var str=in_date.getDate() +'/'+(in_date.getMonth()+1)+'/'+in_date.getFullYear()
document.getElementById('display2').innerHTML=str
}
</script>