dataformat.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //时间格式化
  2. Date.prototype.format = function (format,value) {
  3. /*
  4. * eg:format="yyyy-MM-dd hh:mm:ss";
  5. */
  6. if (!format) {
  7. format = "yyyy-MM-dd hh:mm:ss";
  8. }
  9. if(value==''||value==null){
  10. return '';
  11. }
  12. value = value + ''
  13. var strdata=value.replace(/-/g,"/");
  14. var index=strdata.indexOf(".");
  15. if(index>0)
  16. {
  17. strdata=strdata.substr(0,index);
  18. }
  19. var date= new Date(Date.parse(strdata));
  20. var o = {
  21. "M+" : date.getMonth() + 1, // month
  22. "d+" : date.getDate(), // day
  23. "h+" : date.getHours(), // hour
  24. "m+" : date.getMinutes(), // minute
  25. "s+" : date.getSeconds(), // second
  26. "q+" : Math.floor((date.getMonth() + 3) / 3), // quarter
  27. "S" : date.getMilliseconds()
  28. // millisecond
  29. };
  30. if (/(y+)/.test(format)) {
  31. format = format.replace(RegExp.$1, strdata.substr(4-RegExp.$1.length,RegExp.$1.length));
  32. }
  33. for (var k in o) {
  34. if (new RegExp("(" + k + ")").test(format)) {
  35. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  36. }
  37. }
  38. return format;
  39. };
  40. //对Date的扩展,将 Date 转化为指定格式的String
  41. //月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
  42. //年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  43. //例子:
  44. //(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  45. //(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  46. Date.prototype.Format = function (fmt) { //author: meizz
  47. var o = {
  48. "M+": this.getMonth() + 1, //月份
  49. "d+": this.getDate(), //日
  50. "h+": this.getHours(), //小时
  51. "m+": this.getMinutes(), //分
  52. "s+": this.getSeconds(), //秒
  53. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  54. "S": this.getMilliseconds() //毫秒
  55. };
  56. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  57. for (var k in o)
  58. if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  59. return fmt;
  60. }