自定义的JavaScript时间格式器_日期时间特效

模板酷站

      在网页上显示现在时刻,可以自定义的JavaScript时间格式器,显示星期、几月几号,哪一年,几点钟,完全加入个人的定义格式,而非用JS直接输出,对时间格式要求复杂的前端设计者不妨参观一下。


      <html> <head> <script type="text/javascript" > function DateFormater(expr){ var wd = [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ], M= [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ], utc= false, am= 'AM', pm= 'PM', y,m,j,d,h,i,s,e; this.expr = expr; this.format = function(t){ if(!t.getTime){ return false; } y = utc?t.getUTCFullYear():t.getFullYear(); m = utc?t.getUTCMonth():t.getMonth(); j = utc?t.getUTCDate():t.getDate(); d = utc?t.getUTCDay():t.getDay(); h = utc?t.getUTCHours():t.getHours(); i = utc?t.getUTCMinutes():t.getMinutes(); s = utc?t.getUTCSeconds():t.getSeconds(); e = utc?t.getUTCMilliseconds():t.getMilliseconds(); a = ((h==12 && (m+s+e>0))||h>12)?pm:am; return expr.replace(/\/0?[YyMmjDdHhisea\/]{1}/g, function(){ for(var x=0,l=arguments.length; x<l; x++){ switch(arguments[x]){ case '/Y': return ''+y; case '/y': return (''+y).replace(/\d*(\d{2})/,'$1'); case '/0m': return ''+((m<9?'0'+(m+1): (m+1))); case '/m': return ''+(m+1); case '/M': return M[m]; case '/0j': return ''+(j<10?'0'+j: j); case '/j': return ''+j; case '/d': return ''+d; case '/D': return wd[d]; case '/0H': return ''+(h<10?'0'+h: h); case '/H': return ''+h; case '/0h': h=h>12?h-12:h; return ''+(h<10?'0'+h: h); case '/h': return ''+h>12?h-12:h; case '/0i': return ''+(i<10?'0'+i: i); case '/i': return ''+i; case '/0s': return ''+(s<10?'0'+s: s); case '/s': return ''+s; case '/0e': return ''+(e<10?'00'+e: (e<100?'0'+e: e)); case '/e': return ''+e; case '/a': return ''+a; case '//': return '/'; default: return arguments[x]; } } }); }; this.isUTC = function(u){ return typeof(u)=='boolean'? (utc=u): utc; }; this.AM = function(a){ return am = typeof(a)=='string'? a: am; }; this.PM = function(p){ return pm = typeof(p)=='string'? p: pm; }; this.weekdays = function(){ return _confg(arguments, 'wd', 7); }; this.months = function(){ return _confg(arguments, 'M', 12); } function _confg(args, vrb, s){ var a1 = args[0], a2 = args[1]; if(args.length>2){ return false; } switch( typeof(a1) ){ case 'undefined': return eval(vrb); case 'object': if( a1.length!=s || typeof(a1[0])=='undefined' ){ return false;} for(var i=0,l=a1.length; i<l; i++){ eval(vrb+'[i] = a1[i];'); } break; case 'number': return ( typeof(a2)!='undefined'? false:eval(vrb+'[a1]') ); case 'string': if( typeof(a2)!='number' || typeof(eval(vrb+'[a2]'))=='undefined' ) { return false; } eval(vrb+'[a2] = a1;'); } return true; } } window.onload = function(){ var df = new DateFormater('现在是: /m月/j日,/Y年 /D /a /0h:/0i:/0s'); df.AM('上午'); df.PM('下午'); var datestr = df.format( new Date ); alert( datestr ); }; </script> </head> </html>