'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var formatToDate = _interopDefault(require('./formatToDate'));

/**
 * 格式化时间为给定格式
 * @param {string} fmtStr 格式化字符串
 * 如：'YYYY-MM-DD hh:mm:ss'
 * 'YYYY-MM-DD hh:mm:ss'
 * 'YYYY年MM月DD日 hh时mm分'
 * 'hh:mm YYYY/MM/DD'
 * @param {Date | number | string} time 时间
 * @returns {string}
 *
 * formatDate('YYYY-MM-DD hh:mm:ss', Date.now());
 */
function formatDate(fmtStr, time) {
  var date = formatToDate(time);
  if (!date) return '';
  var timeObj = {
    'Y+': date.getFullYear(),
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    S: date.getMilliseconds(),
    Q: Math.floor((date.getMonth() + 3) / 3)
  };
  var formated = fmtStr;
  Object.keys(timeObj).forEach(function (k) {
    if (new RegExp("(".concat(k, ")")).test(formated)) {
      if (k === 'Y+') {
        formated = formated.replace(RegExp.$1, String(timeObj['Y+']).substr(4 - RegExp.$1.length));
      } else {
        var tmk = timeObj[k];
        var fmt = RegExp.$1.length === 1 ? tmk : "00".concat(tmk).substr(String(tmk).length);
        formated = formated.replace(RegExp.$1, fmt);
      }
    }
  });
  return formated;
}

module.exports = formatDate;
