js时间对象格式化 format(转载)

时间:2021-10-07 21:19:14
  1. /**
  2. * 时间对象的格式化
  3. */
  4. Date.prototype.format = function(format){
  5. /*
  6. * format="yyyy-MM-dd hh:mm:ss";
  7. */
  8. var o = {
  9. "M+": this.getMonth() + 1,
  10. "d+": this.getDate(),
  11. "h+": this.getHours(),
  12. "m+": this.getMinutes(),
  13. "s+": this.getSeconds(),
  14. "q+": Math.floor((this.getMonth() + 3) / 3),
  15. "S": this.getMilliseconds()
  16. }
  17. if (/(y+)/.test(format)) {
  18. format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 -
  19. RegExp.$1.length));
  20. }
  21. for (var k in o) {
  22. if (new RegExp("(" + k + ")").test(format)) {
  23. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  24. }
  25. }
  26. return format;
  27. }