JavaScript的特殊日期处理

孤者浪人 提交于 2020-03-28 22:05:59
很久前写的代码了,偶尔看到贴出来做个备忘,写得有点乱,懒得整理了。

// 根据初始日期和滚动周期及滚动次数来计算终止日期,日期滚动周期,
// 可以是每天(DAY)、每周(WEEK)、每月(MONTH)、每年(YEAR)
// 返回一个日期字符串如'2009-5-9'
 function getFinalDate(startDate,cycleModel,cycleTime,currDate){
  var finalDate="";
  if(validateDate(startDate) && validateDate(currDate)){
   var str_a = startDate+" "+"00:00";
   var tempDate = new Date(str_a.replace(/-/g,"/"));
   
   var currDateStr = currDate+" "+"00:00";
   var currentDate = new Date(currDateStr.replace(/-/g,"/"));
   if(currentDate.getTime() != tempDate.getTime()){
    cycleTime--;
   }
 
   var paramSdate = startDate.split("-");
   var iyear = parseInt(paramSdate[0],10); 
   var imonth = parseInt(paramSdate[1],10);
   var idate = parseInt(paramSdate[2],10);
   if("DAY" == cycleModel){
    var endDate = new Date();
    endDate.setTime(tempDate.getTime()+cycleTime*24*60*60*1000);
    var month = parseInt(endDate.getMonth(),10)+1;
    month = month<10 ? "0"+month : month;
    var day = parseInt(endDate.getDate(),10);
    day = day<10 ? "0"+day : day;
    finalDate = endDate.getYear()+"-"+month+"-"+day;
   }else if("WEEK" == cycleModel){
    var endDate = new Date();
    endDate.setTime(tempDate.getTime()+cycleTime*7*24*60*60*1000);
    var month = parseInt(endDate.getMonth(),10)+1;
    month = month<10 ? "0"+month : month;
    var day = parseInt(endDate.getDate(),10);
    day = day<10 ? "0"+day : day;
    finalDate = endDate.getYear()+"-"+month+"-"+day;  
   }else if("MONTH" == cycleModel){
    var newDate;
    for(var i=1; i<=cycleTime; i++){
     if(imonth == 13){
      iyear+=1;
      imonth = 1;
     }
     newDate = new Date(iyear,imonth+1,0);
     if(newDate.getDate() < idate){
      i--;
     }
     imonth++;
     if(imonth == 13){
      iyear+=1;
      imonth = 1;
     }
    }
    imonth = imonth<10 ? "0"+imonth : imonth;
    idate = idate<10 ? "0"+idate : idate;
    finalDate = iyear + "-" + imonth + "-" + idate;
   }else if("YEAR" == cycleModel){
    var newDate2;
    for(var j=1; j<=cycleTime; j++){
     iyear++;
     newDate2 = new Date(iyear,imonth,0);
     if(newDate2.getDate() < idate){
      j--;    
     }
    }
    imonth = imonth<10 ? "0"+imonth : imonth;
    idate = idate<10 ? "0"+idate : idate;
    finalDate = iyear + "-" + imonth + "-" + idate; 
   }
  }
  //alert(finalDate);
  return finalDate;
 }


// 根据周期模式及开始日期获取两个时间段内的周期次数
// 返回一个次数
 function countCycleTimesFromPeriodDate(startDate,cycleModel,endDate,currDate){
  var str_a = startDate+" "+"00:00";
  var str_b = endDate+" "+"00:00";
  var bDate = new Date(str_a.replace(/-/g,"/"));
  var eDate = new Date(str_b.replace(/-/g,"/"));

  var syear = parseInt(bDate.getYear(),10);
  var smonth = parseInt(bDate.getMonth(),10)+1;
  var sday = parseInt(bDate.getDate(),10);
  var shour = parseInt(bDate.getHours(),10);
  
  var eyear = parseInt(eDate.getYear(),10);
  var emonth = parseInt(eDate.getMonth(),10)+1;
  var eday = parseInt(eDate.getDate(),10);
  
  var cycleTimes=0;
  if(validateDate(startDate) && validateDate(endDate) && validateDate(currDate) && (eDate.getTime()-bDate.getTime())>=0){
   var currDateStr = currDate+" "+"00:00";
   var currentDate = new Date(currDateStr.replace(/-/g,"/"));
   var tempparam = bDate.getTime() != currentDate.getTime() ? 1 : 0;

   if("DAY" == cycleModel){
    cycleTimes = Math.ceil((eDate.getTime()-bDate.getTime())/(24*60*60*1000));
    cycleTimes = cycleTimes+tempparam;
   }else if("WEEK" == cycleModel){
    cycleTimes = Math.floor((eDate.getTime()-bDate.getTime())/(7*24*60*60*1000));
    cycleTimes = cycleTimes+tempparam;
   }else if("MONTH" == cycleModel){
    if(eyear==syear){
     var newDate;
     smonth++;
     for(; smonth<emonth; smonth++){
      newDate = new Date(syear,smonth,0);
      if(sday<=newDate.getDate()){
       cycleTimes++;
      }
     }
     var mt = ((smonth == emonth) && (eday >= sday)) ? 1 : 0;
     cycleTimes += mt;
    }else if(eyear>syear){
       var newDate2;
       smonth++;
      for(; smonth<=12; smonth++){
      newDate2 = new Date(syear,smonth,0);
      if(sday<=newDate2.getDate()){
       cycleTimes++;
      }
      }
      //alert("first:"+cycleTimes);
      if(eyear-syear-1 > 0){
       var temp = eyear-syear-1;
      syear++;
      for(var n=1; n<=temp*12; n++){
       newDate2 = new Date(syear,n,0);
       if(sday<=newDate2.getDate()){
        cycleTimes++;
       }
       if(n%12==0 && eyear-syear-1>0){
        syear++;
       }
      }
      //alert("middle:"+cycleTimes);
      }
      if(eyear-syear-1 == 0){
      for(var k=1; k<=emonth; k++){
       newDate2 = new Date(eyear,k,0);
       if(k==emonth && sday<=newDate2.getDate() && sday<=eday){
        cycleTimes++;
       }else if(k<emonth && sday<=newDate2.getDate()){
        cycleTimes++;
       }
      }
      //alert("end:"+cycleTimes);
      }
    }
    cycleTimes = cycleTimes+tempparam;
   }else if("YEAR" == cycleModel){
      var newDate3;
      if(eyear>syear){
       if(eyear-syear >= 1){
        for(; syear<eyear; syear++){
         newDate3 = new Date(syear,smonth,0);
         if(newDate3.getDate() >= sday){
          cycleTimes++;
         }
        }
        if(0==tempparam){
         cycleTimes--;
        }
        //alert("middle:"+cycleTimes);
       }
       if(syear == eyear && emonth>=smonth){
        var tm = (emonth<smonth) ? 0: emonth>smonth ? 1 : (eday>=sday) ? 1 : 0;
         newDate3 = new Date(eyear,smonth,0);
         if(newDate3.getDate() >= sday){
          cycleTimes += tm;
         }
        //alert("end:"+cycleTimes);
       }
     }else{
      cycleTimes = cycleTimes+tempparam;
     }
   }
  }else if(syear==eyear && smonth==emonth && sday==eday && eDate.getTime()-bDate.getTime()<0){
     cycleTimes = 0;
  }
  return cycleTimes;
 }

var dateRex = /^\d{4}[-]\d{1,2}[-]\d{1,2}[(](\u661f\u671f)[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u65e5][)]$/;
var txtRex = /^([\u4e00-\u9fff]|[0-9]|[a-zA-Z]|[,。、“”!?:;]){1,60}$/;
var numRex = /^\d{1,10}$/;

// 比较用户历史提醒次数与现输入提醒次数迭加后是否超过十次,如果超过则以“yyyy年MM月、yyyy年MM月”的格式返回超过的月份
   function compareMonthForReminderNum(beginDate,cycleModel,endDate,currDate,historyMap){
     var resultStr = "";
     if(validateDate(beginDate) && validateDate(endDate) && validateDate(currDate) && historyArr.length>0 && "" != cycleModel){
        var dateMap = new Map();
     if(compareDate(beginDate,endDate)){
        var bDate = beginDate.split("-");
        var eDate = endDate.split("-");
        var sYear = parseInt(bDate[0],10);
        var sMonth = parseInt(bDate[1],10);
        var sDay = parseInt(bDate[2],10);
        var eYear = parseInt(eDate[0],10);
        var eMonth = parseInt(eDate[1],10);
        var eDay = parseInt(eDate[2],10);
        if((sYear==eYear) && (sMonth==eMonth)){
          sMonth = sMonth < 10 ? "0"+sMonth : sMonth;
          var mkey=sYear+"-"+sMonth;
          var mvalue=countCycleTimesFromPeriodDate(beginDate,cycleModel,endDate,currDate);
          dateMap.put(mkey,mvalue);
          
          alert(dateMap.toString());
        }else if((sYear==eYear) && (eMonth>sMonth)){
         if("DAY"==cycleModel || "MONTH"==cycleModel || "YEAR"==cycleModel){
          dateMap = new Map();
          var counter = 0;
          var newDate = new Date(sYear,sMonth,0);
          var ed = sYear+"-"+sMonth+"-"+newDate.getDate();
          var mkey = sYear+"-"+sMonth;
          counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,ed,currDate);
          var mvalue = counter;
       dateMap.put(mkey,mvalue);
       var tempDate;
          for(var i=sMonth+1; i<eMonth; i++){
             tempDate = new Date(sYear,i,0);
             var edDate = sYear+"-"+i+"-"+tempDate.getDate();
             i = i<10 ? "0"+i : i;
             var mkey=sYear+"-"+i;
             counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,edDate,currDate)-counter;
           var mvalue = counter;
           dateMap.put(mkey,mvalue);
           }
           var mkey=sYear+"-"+eMonth;
           counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,endDate,currDate)-counter;
          var mvalue = counter;
           dateMap.put(mkey,mvalue);
           
           alert(dateMap.toString());
         }else if("WEEK"==cycleModel){
          dateMap = new Map();
          var newDate = new Date(sYear,sMonth,0);
          var ed = sYear+"-"+sMonth+"-"+newDate.getDate();
          var mkey=sYear+"-"+sMonth;
          var mvalue=countCycleTimesFromPeriodDate(beginDate,cycleModel,ed,currDate);
       dateMap.put(mkey,mvalue);
       var wDate = new Date(sYear,sMonth,sDay);
       var weekIndex = wDate.getDay();
       var tempDate;
       for(var i=sMonth+1; i<eMonth; i++){
        var count = 0;
        tempDate = new Date(sYear,i,0);
        var days = tempDate.getDate();
        var dayDate;
        for(var j=1; j<=days; j++){
         dayDate = new Date(sYear,i,j);
         if(weekIndex==dayDate.getDay()){
          count++;
         }
        }
        i = i<10 ? "0"+i : i;
        var mkey=sYear+"-"+i;
        var mvalue=count;
        dateMap.put(mkey,mvalue);
       }
       var ct = 0;
       for(var k=1; k<=eday; k++){
        tempDate = new Date(sYear,emonth,k);
        if(weekIndex==tempDate.getDay()){
         ct++;
        }
       }
       var mkey=sYear+"-"+eMonth;
       var mvalue=ct;
       dateMap.put(mkey,mvalue);
       
       alert(dateMap.toString());
         }
        }else if(sYear<eYear){
          if("DAY"==cycleModel || "MONTH"==cycleModel || "YEAR"==cycleModel){
           dateMap = new Map();
           var counter = 0;
           var newDate = new Date(sYear,sMonth,0);
          var ed = sYear+"-"+sMonth+"-"+newDate.getDate();
          var mkey=sYear+"-"+sMonth;
          counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,ed,currDate);
          var mvalue = counter;
       dateMap.put(mkey,mvalue);
       var tempDate;
       for(var i=sMonth+1; i<=12; i++){
             tempDate = new Date(sYear,i,0);
             var edDate = sYear+"-"+i+"-"+tempDate.getDate();
             i = i<10 ? "0"+i : i;
             var mkey = sYear+"-"+i;
             counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,edDate,currDate)-counter;
           var mvalue = counter;
           dateMap.put(mkey,mvalue);
          }
       for(var j=sYear+1; j<eYear; j++){
        for(var k=1; k<=12; k++){
         tempDate = new Date(j,k,0);
         var edDate = j+"-"+k+"-"+tempDate.getDate();
         k = k<10 ? "0"+k : k;
         var mkey = j+"-"+k;
         counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,edDate,currDate)-counter;
         var mvalue = counter;
         dateMap.put(mkey,mvalue);
        }
       }
       for(var m=1; m<eMonth; m++){
        tempDate = new Date(eYear,m,0);
        var edDate = eYear+"-"+m+"-"+tempDate.getDate();
        m = m<10 ? "0"+m : m;
        var mkey = eYear+"-"+m;
        counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,edDate,currDate)-counter;
        var mvalue = counter;
        dateMap.put(mkey,mvalue);
       }
       var mkey = eYear+"-"+eMonth;
       counter = countCycleTimesFromPeriodDate(beginDate,cycleModel,endDate,currDate)-counter;
       var mvalue = counter;
       dateMap.put(mkey,mvalue);
       
       alert(dateMap.toString());
          }else if("WEEK"==cycleModel){
           dateMap = new Map();
           var newDate = new Date(sYear,sMonth,0);
          var ed = sYear+"-"+sMonth+"-"+newDate.getDate();
          var mkey = sYear+"-"+sMonth;
          var mvalue = countCycleTimesFromPeriodDate(beginDate,cycleModel,ed,currDate);
       dateMap.put(mkey,mvalue);
       var wDate = new Date(sYear,sMonth,sDay);
       var weekIndex = wDate.getDay();
       var tempDate;
       for(var i=sMonth+1; i<=12; i++){
             var count = 0;
        tempDate = new Date(sYear,i,0);
        var days = tempDate.getDate();
        var dayDate;
        for(var j=1; j<=days; j++){
         dayDate = new Date(sYear,i,j);
         if(weekIndex==dayDate.getDay()){
          count++;
         }
        }
        i = i<10 ? "0"+i : i;
        var mkey = sYear+"-"+i;
        var mvalue = count;
        dateMap.put(mkey,mvalue);
          }
          for(var j=sYear+1; j<eYear; j++){
        for(var k=1; k<=12; k++){
         var count = 0;
         tempDate = new Date(j,k,0);
         var days = tempDate.getDate();
         var dayDate;
         for(var f=1; f<=days; f++){
          dayDate = new Date(j,k,f);
          if(weekIndex==dayDate.getDay()){
           count++;
          }
         }
         k = k<10 ? "0"+k : k;
         var mkey = j+"-"+k;
         var mvalue = count;
         dateMap.put(mkey,mvalue);
        }
          }
          for(var m=1; m<eMonth; m++){
        var count = 0;
        tempDate = new Date(eYear,m,0);
        var days = tempDate.getDate();
        var dayDate;
        for(var f=1; f<=days; f++){
         dayDate = new Date(eYear,m,f);
         if(weekIndex==dayDate.getDay()){
          count++;
         }
        }
        m = m<10 ? "0"+m : m;
        var mkey = eYear+"-"+m;
        var mvalue = count;
        dateMap.put(mkey,mvalue);
       }
       var ct = 0;
       for(var n=1; n<=eday; n++){
        tempDate = new Date(sYear,emonth,n);
        if(weekIndex==tempDate.getDay()){
         ct++;
        }
       }
       var mkey = sYear+"-"+eMonth;
       var mvalue = ct;
       dateMap.put(mkey,mvalue);
       
       alert(dateMap.toString());
          }
        }
          
        
        var s = "";
        dateMap.each(
         function(key,value,index){
          s += index+":"+ key+"="+value+"\n";
         }
        );
        alert(s);
      
        for(var dateStr in historyMap){
      s += eval(dateStr)+"------"+historyMap[dateStr]+"\n";   
        }
        alert(s);
        
        for(var dateStr in historyMap){
         var key = eval(dateStr);
         var temp = parseInt(parseInt(historyMap[dateStr],10)+dateMap.get(key),10);   
      if(10<temp){
       resultStr = "、"+key.toString().replace(/-/g,"年")+"月";
      } 
        }
        resultStr = resultStr;
     }
   }
     return resultStr;
   }

 

// 根据输入的日期字符串(yyyy-MM-dd)校验该日期是否正确
 function validateDate(objDate){
  var setDate = objDate;
  var dateRex2 = /^\d{4}[-]\d{1,2}[-]\d{1,2}$/;
  var paramDate = setDate.split("-");
  var tempDate = setDate+" "+"00:00";
  var sDate = new Date(tempDate.replace(/-/g,"/"));
  var sYear = parseInt(paramDate[0],10);
  var sMonth = parseInt(paramDate[1],10);
  var sDay = parseInt(paramDate[2],10);
  var eYear = parseInt(sDate.getYear(),10);
  var eMonth = parseInt(sDate.getMonth(),10)+1;
  var eDay = parseInt(sDate.getDate(),10);
  if(dateRex2.test(setDate) && sYear==eYear && sMonth==eMonth && sDay==eDay){
   return true;
  }
  return false;
 }

// 根据输入的日期字符串(yyyy-MM-dd)转换成yyyy-MM-dd(E)的格式
 function formatterDate(dateStr){
  var newDate = dateStr;
  if(validateDate(dateStr)){
   var currDateStr = dateStr+" "+"00:00";
   var paramSdate = newDate.split("-");
   var iyear = parseInt(paramSdate[0],10); 
   var imonth = parseInt(paramSdate[1],10);
    imonth = imonth < 10 ? "0"+imonth : imonth;
   var idate = parseInt(paramSdate[2],10);
    idate = idate < 10 ? "0"+idate : idate;
   var currentDate = new Date(currDateStr.replace(/-/g,"/"));
   var x = new Array("(星期日)", "(星期一)", "(星期二)");
     var x = x.concat("(星期三)","(星期四)", "(星期五)");
     var x = x.concat("(星期六)");
   var day = currentDate.getDay();
   return (iyear+"-"+imonth+"-"+idate+x[day]);
  }else{
   return newDate;
  } 
 }

 

//判断页面元素是否为空
 function handleParameterStr(obj){
  var paramete=obj;
  if('undefined'==paramete || null==paramete || 0==paramete.value.length || " "==paramete.value){
   paramete="";
  }else{
   paramete=paramete.value;
  }
  return paramete;
 }


 
//js实现类似JAVA的Map功能
 function Map() {   
     /** 存放键的数组(遍历用到) */  
     this.keys = new Array();   
     /** 存放数据 */  
     this.data = new Object();   
        
     /**  
      * 放入一个键值对  
      * @param {String} key  
      * @param {Object} value  
      */  
     this.put = function(key, value) {   
         if(this.data[key] == null){   
             this.keys.push(key);   
         }   
         this.data[key] = value;   
     };   
        
     /**  
      * 获取某键对应的值  
      * @param {String} key  
      * @return {Object} value  
      */  
     this.get = function(key) {   
         return this.data[key];   
     };   
        
     /**  
      * 删除一个键值对  
      * @param {String} key  
      */  
     this.remove = function(key) {   
         this.keys.remove(key);   
         this.data[key] = null;   
     };   
        
     /**  
      * 遍历Map,执行处理函数  
      *   
      * @param {Function} 回调函数 function(key,value,index){..}  
      */  
     this.each = function(fn){   
         if(typeof fn != 'function'){   
             return;   
         }   
         var len = this.keys.length;   
         for(var i=0;i<len;i++){   
             var k = this.keys[i];   
             fn(k,this.data[k],i);   
         }   
     };   
        
     /**  
      * 获取键值数组(类似Java的entrySet())  
      * @return 键值对象{key,value}的数组  
      */  
     this.entrys = function() {   
         var len = this.keys.length;   
         var entrys = new Array(len);   
         for (var i = 0; i < len; i++) {   
             entrys[i] = {   
                 key : this.keys[i],   
                 value : this.data[i]   
             };   
         }   
         return entrys;   
     };   
        
     /**  
      * 判断Map是否为空  
      */  
     this.isEmpty = function() {   
         return this.keys.length == 0;   
     };   
        
     /**  
      * 获取键值对数量  
      */  
     this.size = function(){   
         return this.keys.length;   
     };   
        
     /**  
      * 重写toString   
      */  
     this.toString = function(){   
         var s = "{";   
         for(var i=0;i<this.keys.length;i++,s+=','){   
             var k = this.keys[i];   
             s += k+"="+this.data[k];   
         }   
         s+="}";   
         return s;   
     };   
 }

/**  
 * Map 使用示例
 * var m = new Map();
 * m.put('key1','Google');
 * m.put('key2','baidu');
 * m.put('key3','sohu');
 * alert("init:"+m);
 * 
 * m.put('key1','microsoft');
 * alert("set key1:"+m);
 * 
 * m.remove("key2");
 * alert("remove key2: "+m);
 * 
 * var s ="";
 * m.each(function(key,value,index){
 *   s += index+":"+ key+"="+value+"\n"; 
 * });
 * alert(s);   
 */
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!