惭愧,混迹博客园2年了,还没写过什么。最近不太忙,就写一下Js中Date对象的字符串转换吧。
直接贴代码,欢迎各位拍砖,吐槽!
/*格式化时间
 *formatStr 格式,如:YY-MM-DD hh:mm:ss、Y-M-D h:m:s
 
*只有一个M时,月份小于十时前面不追加零,D、h、m、s雷同
 */
Date.prototype.toStringFormat = 
function (formatStr) {
  if (formatStr == null || formatStr == ‘‘) return 
‘‘;
  var date = this;
  var formatOper = {
    ‘YY‘: function () 
{
      return date.getFullYear();
    }, ‘Y‘: function () 
{
      return formatOperArr[‘YY‘]();
    }, ‘MM‘: function () 
{
      return date.getMonth() + 1 > 9 ? date.getMonth() + 1 : ‘0‘ + 
(date.getMonth() + 1);
    }, ‘M‘: function () {
      return 
date.getMonth();
    }, ‘DD‘: function () {
      return date.getDate() 
> 9 ? date.getDate() : ‘0‘ + date.getDate();
    }, ‘D‘: function () 
{
      return date.getDate();
    }, ‘hh‘: function () {
      return 
date.getHours() > 9 ? date.getHours() : ‘0‘ + date.getHours();
    }, ‘h‘: 
function () {
      return date.getHours();
    }, ‘mm‘: function () 
{
      return date.getMinutes() > 9 ? date.getMinutes() : ‘0‘ + 
date.getMinutes();
    }, ‘m‘: function () {
      return 
date.getMinutes();
    }, ‘ss‘: function () {
      return 
date.getSeconds() > 9 ? date.getSeconds() : ‘0‘ + 
date.getSeconds();
    }, ‘s‘: function () {
      return 
date.getSeconds();
    }
  };
  var formatStrArr = 
formatStr.split(/[^YMDhms]/g);
  var splitArr = 
formatStr.split(/[YMDhms]/g).filter(function (a) { return a != ‘‘; });
  var 
returnStr = ‘‘;
  formatStrArr.forEach(function (value, index) 
{
    returnStr += formatOper[value]() + (splitArr[index] == undefined ? ‘‘ : 
splitArr[index]);
  });
  return returnStr;
};
原文:http://www.cnblogs.com/niuheng/p/3755375.html