欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

日期格式化处理函数集

程序员文章站 2022-07-15 07:51:46
...

使用 

fTimeFormat(item.updateTime, 'Y-M-D')

函数集合暴露

/**
 * @author xxx
 */

/**
 * %s字符串格式替换
 */
function fString(txt) {
  if (!txt || typeof txt !== 'string') return txt;

  var len;
  if ((len = arguments.length)) {
    for (var i = 1; i < len; i++) {
      txt = txt.replace('%s', arguments[i]);
    }
  }
  return txt;
}

/**
 * 数字格式化
 * data 数字,f 格式串
 * 格式串示例:'000.00' 表示整数部分至少三位小数部分两位, .前一个0则不补0
 * 必须指定小数点
 */
function fNumber(data, f) {
  if (/^[0\.]+$/.test(f)) {
    /\./.test(f) || (f += '.');
    f.replace(/^(0*)(\.)(0*)$/, function(f, inter, dot, deci) {
      // 四舍五入保留指定精度小数、转字符串
      data = parseFloat(data).toFixed(deci.length);
      // 补零
      var total = inter.length + (deci.length > 0 ? deci.length + 1 : 0);
      while (data.length < total) {
        data = '0' + data;
      }
    });
    return data;
  } else {
    MOALog.warn('您指定了不规范的格式:' + f);
    return data;
  }
}

/**
 * 获得本周的开始日期
 */
function getWeekStartDate() {
  var now = new Date(); //当前日期
  var nowDayOfWeek = now.getDay(); //今天本周的第几天
  var nowDay = now.getDate(); //当前日
  var nowMonth = now.getMonth(); //当前月
  var nowYear = now.getYear(); //当前年
  nowYear += nowYear < 2000 ? 1900 : 0;

  // 修复周日为0导致计算错误问题
  if (nowDayOfWeek === 0) {
    nowDayOfWeek = 7;
  }

  var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
  return weekStartDate;
}

/**
 * 获得上周的开始日期
 */
function getLastWeekStartDate() {
  var now = new Date(); //当前日期
  var nowDayOfWeek = now.getDay(); //今天本周的第几天
  var nowDay = now.getDate(); //当前日
  var nowMonth = now.getMonth(); //当前月
  var nowYear = now.getYear(); //当前年
  nowYear += nowYear < 2000 ? 1900 : 0;

  // 修复周日为0导致计算错误问题
  if (nowDayOfWeek === 0) {
    nowDayOfWeek = 7;
  }

  var weekStartDate = new Date(
    nowYear,
    nowMonth,
    nowDay - nowDayOfWeek - 7 + 1
  );
  return weekStartDate;
}

function detectType(input) {
  return Object.prototype.toString.call(input).slice(8, -1);
}

function dayStrOfWeek(d) {
  return '周日_周一_周二_周三_周四_周五_周六'.split('_')[d];
}

/**
 * 时间格式化
 * stamp: 时间戳 or Date or '2018-05-20 12:10' or '2018/05/20 12:10'
 * f: 格式串,'smart' 'Y-M-D hh:mm' 'd'(周几) 的组合, smart模式自动识别当日信息提示
 */
function fTimeFormat(stamp, f) {
  var _stamp = stamp;
  if (!stamp) {
    stamp = Date.now();
  }
  if (stamp < 10000000000) {
    stamp = stamp * 1000;
  }
  try {
    // 时间格式化函数
    var dt;
    if (detectType(stamp) === 'Date') {
      dt = stamp;
    } else if (
      typeof stamp === 'number' ||
      (typeof stamp === 'string' && /^\d{13}$/.test(stamp))
    ) {
      dt = new Date(parseInt(stamp));
    } else {
      // 为了兼容IE,需要将2015-01-02变为2015/01/02
      if (stamp && typeof stamp === 'string') {
        stamp = stamp.replace(/\.\d{3}/, '');
      }
      dt = new Date(/-/.test(stamp) ? stamp.replace(/-/g, '/') : stamp);
    }
    if (dt.toJSON()) {
      // 如果是可用的时间对象
      if (/smart/.test(f)) {
        const weekly = true; // 显示两周内的周几
        f = f.replace(/smart/, function() {
          var stamp = dt.getTime(),
            refer = new Date();
          if (stamp <= refer.getTime()) {
            // 过去时间
            // 今天
            refer.setHours(0);
            refer.setMinutes(0);
            refer.setSeconds(0);
            refer.setMilliseconds(0);
            if (stamp >= refer.getTime()) {
              var delta = Math.round((new Date().getTime() - stamp) / 1000); //四舍五入
              var hour = Math.floor(delta / 3600); //向下取整
              var remain = delta % 3600;
              var min = Math.floor(remain / 60),
                sec = remain % 60;

              return fString('hh:mm');
            }
            // 昨天
            refer.setDate(refer.getDate() - 1);
            if (stamp >= refer.getTime()) {
              return fString('昨天');
            }
            if (weekly && stamp > getWeekStartDate().getTime()) {
              return 'd';
            } else if (weekly && stamp > getLastWeekStartDate().getTime()) {
              return '上d';
            } else {
              // 今年
              refer.setDate(1);
              refer.setMonth(0);
              if (stamp >= refer.getTime()) {
                return 'M-D';
              } else {
                return 'y-M-D';
              }
            }
          } else {
            // 未来时间
            // 今天内
            refer.setHours(0);
            refer.setMinutes(0);
            refer.setSeconds(0);
            refer.setMilliseconds(0);
            refer.setDate(refer.getDate() + 1);
            if (stamp <= refer.getTime()) {
              var delta = Math.round((stamp - new Date().getTime()) / 1000); //四舍五入
              var hour = Math.floor(delta / 3600); //向下取整
              var remain = delta % 3600;
              var min = Math.floor(remain / 60),
                sec = remain % 60;
              return fString('hh:mm');
            }
            // 明天
            refer.setDate(refer.getDate() + 1);
            if (stamp <= refer.getTime()) {
              return fString('明天 hh:mm');
            } else {
              // 今年
              refer.setDate(1);
              refer.setMonth(12);
              if (stamp <= refer.getTime()) {
                return 'M-D';
              } else {
                return 'y-M-D';
              }
            }
          }
          // 更早
          return 'Y-M-D';
        });
      }
      return f
        .replace(/hh/, fNumber(dt.getHours(), '00'))
        .replace(/mm/, fNumber(dt.getMinutes(), '00'))
        .replace(/ss/, fNumber(dt.getSeconds(), '00'))
        .replace(/h/, dt.getHours())
        .replace(/m/, dt.getMinutes())
        .replace(/s/, dt.getSeconds())
        .replace(/d/, dayStrOfWeek(dt.getDay())) // 周几
        .replace(/MM/, fNumber(dt.getMonth() + 1, '00'))
        .replace(/DD/, fNumber(dt.getDate(), '00'))
        .replace(
          /y/,
          dt
            .getFullYear()
            .toString()
            .substring(2)
        )
        .replace(/Y/, dt.getFullYear())
        .replace(/M/, dt.getMonth() + 1)
        .replace(/D/, dt.getDate());
    } else {
      // 如果无法转化为时间对象,原样返回
      MOALog.warn('不是可用的时间对象:' + _stamp);
      return _stamp;
    }
  } catch (e) {
    return _stamp;
  }
}

function parseDate(stamp) {
  var dt;
  if (detectType(stamp) === 'Date') {
    dt = stamp;
  } else if (
    typeof stamp === 'number' ||
    (typeof stamp === 'string' && /^\d{13}$/.test(stamp))
  ) {
    dt = new Date(parseInt(stamp));
  } else if (stamp && /^\d{4}\d{1,2}\d{1,2}$/.test(stamp)) {
    var reg = new RegExp(/^(\d{4})(\d{1,2})(\d{1,2})$/);
    var rst = reg
      .exec(stamp)
      .slice(1)
      .join('/');
    return new Date(rst);
  } else {
    // 为了兼容IE,需要将2015-01-02变为2015/01/02
    if (stamp && typeof stamp === 'string') {
      stamp = stamp.replace(/\.\d{3}/, '');
    }
    dt = new Date(/-/.test(stamp) ? stamp.replace(/-/g, '/') : stamp);
  }
  return dt;
}

// 获得最接近的未来时间,半小时整点间隔
function getNearbyFeatureTime() {
  var date = new Date();
  if (date.getMinutes() < 30) {
    date.setMinutes(30);
  } else {
    date.setMinutes(60);
  }
  date.setSeconds(0);
  date.setMilliseconds(0);
  return date;
}

function formatSeconds(seconds) {
  // hh:mm:ss
  seconds || (seconds = 0);
  var sec = seconds % 60;
  seconds = (seconds - sec) / 60;
  var min = seconds % 60;
  var hour = (seconds - min) / 60;
  return (
    fNumber(hour, '00') + ':' + fNumber(min, '00') + ':' + fNumber(sec, '00')
  );
}

export {
  getWeekStartDate,
  getLastWeekStartDate,
  detectType,
  fNumber,
  fString,
  fTimeFormat,
  parseDate,
  formatSeconds,
  getNearbyFeatureTime
};

 

相关标签: 日期格式化