dateFormate.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * author: kwong
  3. * 对Date的扩展,将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
  4. 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
  5. Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
  6. * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
  7. * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
  8. * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
  9. * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  10. * */
  11. Date.prototype.pattern=function(fmt) {
  12. var o = {
  13. "M+" : this.getMonth()+1, //月份
  14. "d+" : this.getDate(), //日
  15. "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
  16. "H+" : this.getHours(), //小时
  17. "m+" : this.getMinutes(), //分
  18. "s+" : this.getSeconds(), //秒
  19. "q+" : Math.floor((this.getMonth()+3)/3), //季度
  20. "S" : this.getMilliseconds() //毫秒
  21. };
  22. // var week = {
  23. // "0" : "/u65e5",
  24. // "1" : "/u4e00",
  25. // "2" : "/u4e8c",
  26. // "3" : "/u4e09",
  27. // "4" : "/u56db",
  28. // "5" : "/u4e94",
  29. // "6" : "/u516d"
  30. // };
  31. var week = {
  32. "0" : "日",
  33. "1" : "一",
  34. "2" : "二",
  35. "3" : "三",
  36. "4" : "四",
  37. "5" : "五",
  38. "6" : "六"
  39. };
  40. if(/(y+)/.test(fmt)){
  41. fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  42. }
  43. if(/(E+)/.test(fmt)){
  44. fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "星期" : "周") : "")+week[this.getDay()+""]);
  45. }
  46. for(var k in o){
  47. if(new RegExp("("+ k +")").test(fmt)){
  48. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  49. }
  50. }
  51. return fmt;
  52. }