JavaScript Date and Time

Javascript has a lot of inbuilt methods you can use to get the date and time. The first thing you need to do is to create a new Date object:

var d = new Date();

Example to get the current date:

<script>

var d = new Date();

document.write(d);

var d1=d.getDay();

var m=d.getMonth()+1;

var y=d.getFullYear();

document.write(“Today is “ + d1 + “/” +m + “/” +y);

</script>

Example – Age Calculator
<html>

<head>

<script>

Function age() {

Var byear =prompt(“enter Year of Birth ?”);

var d = new Date();

var y=d.getFullYear();

var q=y-byear;

alert(“You are  “+q + “ Years Old”);

}  </script>

</head>

<body>

<h2>Age Calculator Example </h2>

<input type=”button” value=”Calculate Age” onclick=”age()”>

</body>

</html>

Week Days Example – Switch Case

<script>

function viewday()

{

var d=new Date().getDay();

switch(d)

{

case 0:

alert(“sunday”);

break;

case 1:

alert(“Monday”);

break;

case 2:

alert(“Tuesday”);

break;

case 3:

alert(“Wednesday”);

break;

case 4:

alert(“Thursday”);

break;

case 5:

alert(“Friday”);

break;

default:

alert(“Saturday”);

break;

}

}

</script>

<input type=”button” value=”Get Day” onclick=” viewday()”>

Leave a Reply

Your email address will not be published.

Enjoy the tutorial? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+2k
Google+
http://hirdeshbhardwaj.com/2017/04/25/javascript-dates-time
YouTube63
YouTube