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

来源:互联网 发布:神优化单机游戏2016 编辑:程序博客网 时间:2024/06/08 03:11

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

用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;

}

原创粉丝点击