码迷,mamicode.com
首页 > Web开发 > 详细

Js中Date格式化为字符串

时间:2014-06-29 14:48:18      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:get   os   cti   代码   c   for   

惭愧,混迹博客园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;
};

Js中Date格式化为字符串,布布扣,bubuko.com

Js中Date格式化为字符串

标签:get   os   cti   代码   c   for   

原文地址:http://www.cnblogs.com/niuheng/p/3755375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!