---
title: "日期字符串转化为日期对象，日期格式化"
author: "dywjavaeyw"
date: "2011-03-21T17:52:44Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2011-03-21T17:53:42Z"
id: 969697
url: "https://dywjavaeyw.iteye.com/blog/969697"
---

**日期字符串转化为日期对象
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");**