ITeye博客

日期字符串转化为日期对象,日期格式化

dywjavaeyw · 2011-03-21 17:52 · js · Web前端 · Markdown

**日期字符串转化为日期对象 String.prototype.toDate = function() { 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] = this.substring(tmp.indexOf(RegExp.$1), tmp.indexOf(RegExp.$1) +RegExp.$1.length); } } return new Date(result, result - 1, result, result, result, result); }

/**

  • 时间对象的格式化;
    /
    Date.prototype.format = function(format) {
    /

    • eg:format="YYYY-MM-dd hh:mm:ss";
      */
      var o = {
      "M+" :this.getMonth() + 1, // month
      "d+" :this.getDate(), // day
      "h+" :this.getHours(), // hour
      "m+" :this.getMinutes(), // minute
      "s+" :this.getSeconds(), // second
      "q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
      "S" :this.getMilliseconds()
      // millisecond
      }

    if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "")
    .substr(4 - RegExp.$1.length));
    }

    for ( var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o
    : ("00" + o).substr(("" + o).length));
    }
    }
    return format;
    }

eg:var d1 = startDateStr.toDate().format("yyyy-MM-dd");**

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。