Home Free Templets Works Mind Chiller Photo Gallery Family & Friends Links
 
 
   
     
           
   
How To calculate Date in JavaScript
     
           
   

In this tutorial we will learn how to display Date and Time in Javascript.
The simplest way to dispaly a date in JavaScript is to create an instance of the Date object.

<script language="javascript">
d1 = new Date();
document.write(d1);
// Mon Feb 12 22:07:13 UTC+0530 2007
</script>

The other forms of Date() functions in JavaScript are

date1= new Date(1970,9,17);
//parameters are Year,Month,Day
date2=new Date(1970,9,17,13,45,0);
//parameters are Year,Month,Day,Hour,Minute,Second
date2=new Date(October 17,1970,13,45,0);
//parameters are Month,Day,Year,Hour,Minute,Second

There are some additional functions in JavaScript to get the date informations individually. These are
Assuming curent date is Mon Feb 12 22:07:13 UTC+0530 2007
getYear() :- returns current year i.e.
getMonth() :- returns current month i.e. (Month index starts from 0 for January)
getDate() :- returns current day i.e.
getDay() :- returns current day of the week i.e. (0 for sunday, 1 for monday etc)
getHours() :- returns current hour i.e. (24 Hour format)
getMinutes() :- returns current minute i.e.
getSeconds() :- returns current seconds i.e.
getTime() :- returns the number of milliseconds i.e. since January 1970 00:00:00

All this functions have corresponding set of functions in the format setYear(arg), setDate(arg),setMonth(arg) etc through which you can set the corresponding date and time in JavaScript.

Here are some code snippet which describes how to show the dates in formatted manner in JavaScript.

Display date in dd/mm/yyyy format

<script language="javascript">
var d1;
d1 = new Date();
document.write(d1.getDate() + "/" + d1.getMonth() + "/" + d1.getYear() );
<script>

Display time in hh:mm:ss format (24 Hour)

<script language="javascript">
var d1;
d1 = new Date();
document.write(d1.getHours() + ":" + d1.getMinutes() + ":" + d1.getSeconds() );
<script>

Display time in hh:mm:ss format (12 Hours + AM/PM)

<script language="javascript">
var d1;
d1 = new Date();
var h;
h= d1.getHours();
if (h>12)
document.write((h-12) + "::" + d1.getMinutes() + "::" + d1.getSeconds() + "PM");
else
document.write(d1.getHours() + "/" + d1.getMinutes() + "/" + d1.getSeconds() + "AM");
</script>

Getting Day of the week by name using JavaScript
<script language="javascript">
var d1;
d1 = new Date();
var a2= new Array("Sun","Mon","Tues","Wed","Thurs","Fri","Sat");
document.write(a2[d1.getDay()]);
</script>



So , that's it . Hope you have enjoyed the tutorial. Thank You.


Back to Tutorial Index page

Your comments are most welcome admin@koderguru.com