Friday, August 20, 2010

DateAdd : reusable Javascript function

 

While looking for a Javascript equivalent of DataAdd VB or SQL method, I came across this function which is working flawlessly. Please visit the forum post to view it directly and also as follow:

   1: function DateAdd(timeU,byMany,dateObj) {
   2:     var millisecond=1;
   3:     var second=millisecond*1000;
   4:     var minute=second*60;
   5:     var hour=minute*60;
   6:     var day=hour*24;
   7:     var year=day*365;
   8:  
   9:     var newDate;
  10:     var dVal=dateObj.valueOf();
  11:     switch(timeU) {
  12:         case "ms": newDate=new Date(dVal+millisecond*byMany); break;
  13:         case "s": newDate=new Date(dVal+second*byMany); break;
  14:         case "mi": newDate=new Date(dVal+minute*byMany); break;
  15:         case "h": newDate=new Date(dVal+hour*byMany); break;
  16:         case "d": newDate=new Date(dVal+day*byMany); break;
  17:         case "y": newDate=new Date(dVal+year*byMany); break;
  18:     }
  19:     return newDate;
  20: }

No comments: