1. 程式人生 > >關於js中的date處理

關於js中的date處理

span format) == sta ear 都是 replace string test

  1. 關於使用的:
  2. /**
  3. * js時間對象的格式化;
  4. * eg:format="yyyy-MM-dd hh:mm:ss";
  5. */
  6. Date.prototype.format = function (format) { //prototype 意思:原型 js中的處理都是根據原型來的,這裏等於給Date對象加了一個方法,在後面實例後可以直接調用了
  7. var o = {
  8. "M+": this.getMonth() + 1, //month
  9. "d+": this.getDate(), //day
  10. "h+": this.getHours(), //hour
  11. "m+": this.getMinutes(), //minute
  12. "s+": this.getSeconds(), //second
  13. "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
  14. "S": this.getMilliseconds() //millisecond
  15. }
  16. var week=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
  17. if (/(y+)/.test(format)) {
  18. format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  19. }
  20. if (/(w+)/.test(fmt)){
  21. fmt = fmt.replace(RegExp.$1, week[this.getDay()]);
  22. }
  23. for (var k in o) {
  24. if (new RegExp("(" + k + ")").test(format)) {
  25. format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  26. }
  27. }
  28. return format;
  29. }
  30. /**
  31. *js中更改日期
  32. * y年, m月, d日, h小時, n分鐘,s秒
  33. */
  34. Date.prototype.add = function (part, value) {
  35. value *= 1;
  36. if (isNaN(value)) {
  37. value = 0;
  38. }
  39. switch (part) {
  40. case "y":
  41. this.setFullYear(this.getFullYear() + value);
  42. break;
  43. case "m":
  44. this.setMonth(this.getMonth() + value);
  45. break;
  46. case "d":
  47. this.setDate(this.getDate() + value);
  48. break;
  49. case "h":
  50. this.setHours(this.getHours() + value);
  51. break;
  52. case "n":
  53. this.setMinutes(this.getMinutes() + value);
  54. break;
  55. case "s":
  56. this.setSeconds(this.getSeconds() + value);
  57. break;
  58. default:
  59. }
  60. }

用法:

  1. var start = new Date();
  2. start.add("d", -1); //昨天
  3. start.format(‘yyyy/MM/dd w‘); //格式化
  4. start.add("m", -1); //上月

1、先實例Date對象,表示獲取一個時間,可以指定

2、用add方法來對時間進行處理

3、用format方法來進行指定要返回的日期格式

關於js中的date處理