Js中Date格式化為字串

來源:互聯網
上載者:User

標籤: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;
};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.