关于js中的date处理

  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方法来进行指定要返回的日期格式

转载于:https://www.cnblogs.com/ktbdream/p/7669668.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值