码迷,mamicode.com
首页 > Web开发 > 详细

关于js中的date处理

时间:2017-10-15 11:11:25      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:alt   对象   实例   bst   regex   时间   star   cond   tar   

  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. /** 
  32. *js中更改日期  
  33. * y年, m月, d日, h小时, n分钟,s秒  
  34. */  
  35. Date.prototype.add = function (part, value) {  
  36.     value *= 1;  
  37.     if (isNaN(value)) {  
  38.         value = 0;  
  39.     }  
  40.     switch (part) {  
  41.         case "y":  
  42.             this.setFullYear(this.getFullYear() + value);  
  43.             break;  
  44.         case "m":  
  45.             this.setMonth(this.getMonth() + value);  
  46.             break;  
  47.         case "d":  
  48.             this.setDate(this.getDate() + value);  
  49.             break;  
  50.         case "h":  
  51.             this.setHours(this.getHours() + value);  
  52.             break;  
  53.         case "n":  
  54.             this.setMinutes(this.getMinutes() + value);  
  55.             break;  
  56.         case "s":  
  57.             this.setSeconds(this.getSeconds() + value);  
  58.             break;  
  59.         default:  
  60.    
  61.     }  
  62. }  

 

用法:

  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处理

标签:alt   对象   实例   bst   regex   时间   star   cond   tar   

原文地址:http://www.cnblogs.com/ktbdream/p/7669668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!