javascript 处理字符串与日期的转换

对中国人来说,日期有自己特定的格式

用Date.toString() 和 new Date(String),总是不能很好的得到自己想要的结果,结合网上搜索的内容和自己的想法,写了两个扩展用的prototype。

 

 /* 将字符串转换成日期时间,有默认格式 */

String.prototype.toDate = function(style) {

if (style == null) style = 'yyyy-MM-dd hh:mm:ss';

    var compare = {

         'y+' : 'y',

         'M+' : 'M',

         'd+' : 'd',

         'h+' : 'h',

         'm+' : 'm',

         's+' : 's'

    };

    var result = {

        'y' : '',

        'M' : '',

        'd' : '',

        'h' : '00',

        'm' : '00',

        's' : '00'

    };

    var tmp = style;

    for (var k in compare) {

        if (new RegExp('(' + k + ')').test(style)) {

              result[compare[k]] = this.substring(tmp.indexOf(RegExp.$1), tmp.indexOf(RegExp.$1) +RegExp.$1.length);

       }

    }

    return new Date(result['y'], result['M'] - 1, result['d'], result['h'], result['m'], result['s']);

};


/* 将日期时间转换成特定格式显示 */

Date.prototype.toText = function(style){

    if (style == null) style = 'yyyy-MM-dd hh:mm';

    var compare = {

         'y+' : 'y', 

         'M+' : 'M',  //格式 月份:01到12

         'o+' : 'o',  //格式 月份:1 到12

         'd+' : 'd',  //格式 天 : 01到31

         'D+' : 'D',  //格式 天 : 1 到31

         'h+' : 'h',  //格式 小时:00到23

         'H+' : 'H',  //格式 小时:0 到23

         'm+' : 'm',  //格式 分钟:00到59

         'i+' : 'i',  //格式 分钟:0 到59

         's+' : 's',  //格式 秒 : 00到59

         'S+' : 'S'   //格式 秒 : 0到59

    };

    var result = {

         'y':this.getFullYear(),

         'M':(this.getMonth() < 9) ? ("0" + (1+this.getMonth())) : (1+this.getMonth()),

         'o':(1+this.getMonth()),

         'd':(this.getDate() < 10) ? ("0" + this.getDate()) : this.getDate(),

         'D':this.getDate(),

         'h':(this.getHours()< 10) ? ("0" + this.getHours()):this.getHours(),

         'H':this.getHours(),

         'm':(this.getMinutes()<10)? ("0" + this.getMinutes()):this.getMinutes(),

         'i':this.getMinutes(),

         's':(this.getSeconds()<10)? ("0" + this.getSeconds()):this.getSeconds(),

         'S':this.getSeconds()

    };

    var tmp = style;

    for( var k in compare){

        if (new RegExp('(' + k + ')').test(style)) {

            tmp = tmp.replace(RegExp.$1,result[compare[k]]);

       };

   };

   return tmp;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值