Wednesday, August 25, 2010

Displaying Current Date using Javascript

We can get the current date using the javascript build-in functions. To get the current date we have to use

 var dt new Date()  

in javascript.This creates one date type variable which holds all the date related informations like date,moth,year,time etc,.
Displaying this in any component or in alert will give information like

 Wed Aug 25 2010 13:42:41 GMT+0530 (India Standard Time)  

There are various methods are available in javascript to get the details only what we needed from this .We can use these methods like

 dt.getMonth();  
 dt.getDate();  

First one(getMonth()) gives only current month(0-11),getDate() gives the current date.Here is the sample to get MM/DD/YYYY for the current date in javascript

   var curr_date=new Date();   
   var month=curr_date.getMonth()+1;  
   var day=curr_date.getDate();  
   var year=curr_date.getYear();  
   // Y2K compliant  
   if (year < 1000) year +=1900;  
   document.getElementById(component).value = month + "/" + day + "/" + year;  


In this the getYear() method will return non Y2K compliant year(110 for 2010 ! ) to make this Y2K complian ,we need to add 1900 with that.

No comments:

Post a Comment