[Javascript] guessing date format

Shawn Milo milo at linuxmail.org
Wed Jun 2 13:37:55 CDT 2004


If anyone played with that Javascript popup calendar I 
posted a little while back, they may be interested in this.

Because we use this script in so many apps, with different
date formats (numeric, string, and date data types), I had
a phone call today about the calendar script returning 
a date in a format which didn't work with that particular
app.  So I re-wrote the function which populates the text box.  

I'm just sort of throwing this out there for general viewing.
It works fine, but if anyone has any comments or suggestions,
that would be just dandy, as well.

Shawn


//function re-written by skm on 20040602
//New feature:  function tries to guess
//which format to use for the date, based
//upon the original value in the text box.
//
//Also, if the original box is blank, it tries
//to guess which format to use by looking at
//all of the objects on the form until it
//finds a text box which isn't blank.  It then
//places that value into the original box.
//Worst-case scenario, it just defaults
//to the mm/dd/yyyy format.
//
function fSetDate(iYear, iMonth, iDay){

   var finishedDate = '';
   var iCount;
   
   if (iMonth < 10){ iMonth = '0' + iMonth;}
   if (iDay < 10){ iDay = '0' + iDay;}

   if (gdCtrl.value == ''){
      for (iCount=0; iCount<document.forms[0].length; iCount++){
         if ((document.forms[0].elements[iCount].type == 'text') && (document.forms[0].elements[iCount].value != '')){
            gdCtrl.value = document.forms[0].elements[iCount].value;
            break;   
         }
      }
   }
   
   
   
   if (gdCtrl.value.match(/^\d{4}-\d{2}-\d{2}$/)){
   
      finishedDate = iYear;
      finishedDate = finishedDate + '-' + iMonth;
      finishedDate = finishedDate + '-' + iDay;
   
   }else if (gdCtrl.value.match(/^\d{4}\d{2}\d{2}$/)){
   
      finishedDate = iYear;
      finishedDate = finishedDate + '' + iMonth;
      finishedDate = finishedDate + '' + iDay;
   
   }else{
      finishedDate = iMonth+"/"+iDay+"/"+iYear;
   }

   
   gdCtrl.value =  finishedDate;
   
   fHideCalendar();
   
}






More information about the Javascript mailing list