论坛首页 Web前端技术论坛

JavaScript日期格式化

浏览 20816 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (7)
作者 正文
   发表时间:2010-03-17   最后修改:2010-03-23
DateFormat = (function(){   
 var SIGN_REGEXP = /([yMdhsm])(\1*)/g;   
 var DEFAULT_PATTERN = 'yyyy-MM-dd';   
 function padding(s,len){   
  var len =len - (s+'').length;   
  for(var i=0;i<len;i++){s = '0'+ s;}   
  return s;   
 };
 return({   
  format: function(date,pattern){   
   pattern = pattern||DEFAULT_PATTERN;   
   return pattern.replace(SIGN_REGEXP,function($0){   
    switch($0.charAt(0)){   
     case 'y' : return padding(date.getFullYear(),$0.length);   
     case 'M' : return padding(date.getMonth()+1,$0.length);   
     case 'd' : return padding(date.getDate(),$0.length);   
     case 'w' : return date.getDay()+1;   
     case 'h' : return padding(date.getHours(),$0.length);   
     case 'm' : return padding(date.getMinutes(),$0.length);   
     case 's' : return padding(date.getSeconds(),$0.length);   
    }   
   });   
  },   
  parse: function(dateString,pattern){   
   var matchs1=pattern.match(SIGN_REGEXP);   
   var matchs2=dateString.match(/(\d)+/g);   
   if(matchs1.length==matchs2.length){   
    var _date = new Date(1970,0,1);   
    for(var i=0;i<matchs1.length;i++){
     var _int = parseInt(matchs2[i]);
     var sign = matchs1[i];
    switch(sign.charAt(0)){   
     case 'y' : _date.setFullYear(_int);break;   
     case 'M' : _date.setMonth(_int-1);break;   
     case 'd' : _date.setDate(_int);break;   
     case 'h' : _date.setHours(_int);break;   
     case 'm' : _date.setMinutes(_int);break;   
     case 's' : _date.setSeconds(_int);break;   
    }
    }   
    return _date;   
   }   
   return null;   
  }   
 });   
})();   

 //将一个 Date 格式化为日期/时间字符串。
 alert(  DateFormat.format(new Date(),'yyyy年MM月dd日')  );
 //从给定字符串的开始分析文本,以生成一个日期。
 alert(  DateFormat.parse('2010-03-17','yyyy-MM-dd')  );

 

 

 

备注:parse方法处理的有点不好,还有点问题。 类似yyyyMMdd之类没有分割的格式无法解析。

 

   发表时间:2010-03-18  
头都晕了,就为了个格式化就这么麻烦......
0 请登录后投票
   发表时间:2010-03-19  
这代码太复杂了
0 请登录后投票
   发表时间:2010-03-19  
这的没有必要这样写 太麻烦了
0 请登录后投票
   发表时间:2010-03-19  
看看这个,比你简单:

http://hi.baidu.com/jindw/blog/item/2346c158c912b384810a1813.html
0 请登录后投票
   发表时间:2010-03-19  
Date.prototype.format = function(style){
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "w+": "天一二三四五六".charAt(this.getDay()), //week
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(style)) {
        style = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(style)) {
            style = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return style;
};

这个是不是好点呢
1 请登录后投票
   发表时间:2010-03-19  
d: "String.leftPad(this.getDate(), 2, '0')",
        D: "Date.getShortDayName(this.getDay())", // get localised short day name
        j: "this.getDate()",
        l: "Date.dayNames[this.getDay()]",
        N: "(this.getDay() ? this.getDay() : 7)",
        S: "this.getSuffix()",
        w: "this.getDay()",
        z: "this.getDayOfYear()",
        W: "String.leftPad(this.getWeekOfYear(), 2, '0')",
        F: "Date.monthNames[this.getMonth()]",
        m: "String.leftPad(this.getMonth() + 1, 2, '0')",
        M: "Date.getShortMonthName(this.getMonth())", // get localised short month name
        n: "(this.getMonth() + 1)",
        t: "this.getDaysInMonth()",
        L: "(this.isLeapYear() ? 1 : 0)",
        o: "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))",
        Y: "this.getFullYear()",
        y: "('' + this.getFullYear()).substring(2, 4)",
        a: "(this.getHours() < 12 ? 'am' : 'pm')",
        A: "(this.getHours() < 12 ? 'AM' : 'PM')",
        g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
        G: "this.getHours()",
        h: "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
        H: "String.leftPad(this.getHours(), 2, '0')",
        i: "String.leftPad(this.getMinutes(), 2, '0')",
        s: "String.leftPad(this.getSeconds(), 2, '0')",
        u: "String.leftPad(this.getMilliseconds(), 3, '0')",
        O: "this.getGMTOffset()",
        P: "this.getGMTOffset(true)",
        T: "this.getTimezone()",
        Z: "(this.getTimezoneOffset() * -60)",
1 请登录后投票
   发表时间:2010-03-21  
Relucent 写道
DateFormat = {
 format : function(date,formatter){
  if(date==null){return null;};
  if(formatter==null){formatter = "yyyy-MM-dd";};
  var year = date.getYear().toString();
  var month = (date.getMonth() + 1).toString();
  var day = date.getDate().toString();
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  var seconds = date.getSeconds().toString();
  var yearMarker = formatter.replace(/[^y]/g,'');
  var monthMarker = formatter.replace(/[^M]/g,'');
  var dayMarker = formatter.replace(/[^d]/g,'');
  var hoursMarker = formatter.replace(/[^h]/g,'');
  var minutesMarker = formatter.replace(/[^m]/g,'');
  var secondsMarker = formatter.replace(/[^s]/g,'');
  if(yearMarker.length == 2){year = year.substring(2,4);};
  if(monthMarker.length > 1 && month.length==1){month = "0" + month;};
  if(dayMarker.length > 1 && day.length==1){day = "0" + day;};
  if(hoursMarker.length > 1 && hours.length==1){hours = "0" + hours;};
  if(minutesMarker.length > 1 && minutes.length==1){minutes = "0" + minutes;};
  if(secondsMarker.length > 1 && seconds.length==1){seconds = "0" + seconds;};
  if(yearMarker.length>0){formatter = formatter.replace(yearMarker,year);}
  if(monthMarker.length>0){formatter = formatter.replace(monthMarker,month);};
  if(dayMarker.length>0){formatter = formatter.replace(dayMarker,day);};
  if(hoursMarker.length>0){formatter = formatter.replace(hoursMarker,hours);};
  if(minutesMarker.length>0){formatter = formatter.replace(minutesMarker,minutes);};   
  if(secondsMarker.length>0){formatter = formatter.replace(secondsMarker,seconds);};
  return formatter;
 },
 parse : function(dateString,formatter){
  var today = new Date();
  if(dateString==null){return today;};
  if(formatter==null){formatter = "yyyy-MM-dd";};
  var yearMarker = formatter.replace(/[^y]/g,'');
  var monthMarker = formatter.replace(/[^M]/g,'');
  var dayMarker = formatter.replace(/[^d]/g,'');
  var hoursMarker = formatter.replace(/[^h]/g,'');
  var minutesMarker = formatter.replace(/[^m]/g,'');
  var secondsMarker = formatter.replace(/[^s]/g,'');
  var yearPosition = formatter.indexOf(yearMarker);
  var yearLength = yearMarker.length;
  var year = parseInt( dateString.substring(yearPosition ,yearPosition + yearLength) );
  if(isNaN(year)){
   year = today.getYear();
  }else{
   if( yearLength == 2){
    if(year < 50 ){
     year += 2000;
    }else{
     year += 1900;
    };
   };
  };
  var monthPosition = formatter.indexOf(monthMarker);
  var month = parseInt( dateString.substring(monthPosition,monthPosition + monthMarker.length) );
  if(isNaN(month)){
   month = today.getMonth();
  }else{
   month-=1
  };
  var dayPosition = formatter.indexOf(dayMarker);
  var day = parseInt( dateString.substring( dayPosition,dayPosition + dayMarker.length ) );
  if(isNaN(day)){
   day = today.getDate();
  }else{
  };
  var hoursPosition = formatter.indexOf(hoursMarker);
  var hours = parseInt( dateString.substring( hoursPosition,hoursPosition + hoursMarker.length ) );
  if(isNaN(hours)){
   hours = 0;
  };
  var minutesPosition = formatter.indexOf(minutesMarker);
  var minutes = parseInt( dateString.substring( minutesPosition,minutesPosition + minutesMarker.length ) );
  if(isNaN(minutes)){
   minutes = 0;
  };
  var secondsPosition = formatter.indexOf(secondsMarker);
  var seconds = parseInt( dateString.substring( secondsPosition,secondsPosition + secondsMarker.length ) );
  if(isNaN(seconds)){
   seconds = 0;
  };
  return new Date(year,month,day, hours,minutes,seconds);
 }
};

 

 //将一个 Date 格式化为日期/时间字符串。
 alert(  DateFormat.format(new Date(),'yyyy年MM月dd日')  );
 //从给定字符串的开始分析文本,以生成一个日期。
 alert(  DateFormat.parse('20100317','yyyyMMdd')  );

 

 

 

0 请登录后投票
   发表时间:2010-03-22  
写得还可以,好不好是另外一说嘛,首先要鼓励同时也感谢兄弟和大家一起分享你的成功!
1 请登录后投票
   发表时间:2010-03-22  
感觉代码确实多了这么一点点!
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics