js日期标准转换格式、日期汉字转换格式

1.日期标准转换格式

// 自定义时间格式 :format
// "yyyy-MM-dd HH:mm:ss";"yyyy-MM-dd-HH-mm-ss"
// "yyyy-MM-ddTHH:mm:ss" ....
function formatDate (time, format) {
  if (!time) {
    return ''
  }

  if (typeof time === 'string') {
    time = time.replace('T', ' ').replace(new RegExp('-', 'gm'), '/')
  }

  let t = new Date(time)

  if (t.getTime() === 0) {
    t = new Date()
  }

  let tf = function (i) {
    return (i < 10 ? '0' : '') + i
  }
  if (!format) {
    format = 'yyyy-MM-dd HH:mm:ss'
  }

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (type) {
    switch (type) {
      case 'yyyy':
        return tf(t.getFullYear())
      case 'MM':
        return tf(t.getMonth() + 1)
      case 'mm':
        return tf(t.getMinutes())
      case 'dd':
        return tf(t.getDate())
      case 'HH':
        return tf(t.getHours())
      case 'ss':
        return tf(t.getSeconds())
    }
  })
}

2、日期汉字转换格式 昨天 前天 等等

// 自定义时间格式 :format
// 推荐format "yyyyMMdd HH:mm:ss";
// 推荐format "yyyyMMdd";
function formatDateSemantic (time, format) {
  if (!time) {
    return ''
  }

  if (typeof time === 'string') {
    time = time.replace('T', ' ').replace(new RegExp('-', 'gm'), '/')
  }

  let t = new Date(time)

  if (t.getTime() === 0) {
    t = new Date()
  }

  let tf = function (i) {
    return (i < 10 ? '0' : '') + i
  }
  if (!format) {
    format = 'yyyyMMdd HH:mm:ss'
  }

  let nowTime = new Date();
  let currentYear = nowTime.getFullYear();
  let currentMonth = nowTime.getMonth();
  let currentDate = nowTime.getDate();

  let sameYear = currentYear === t.getFullYear();
  let sameMonth = currentMonth === t.getMonth();


  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (type) {
    switch (type) {
      case 'yyyy':
        return currentYear === t.getFullYear() ? "" : tf(t.getFullYear()) + '年';
      case 'MM':
        return (sameYear && sameMonth) ? "" : tf(t.getMonth() + 1) + '月';
      case 'dd':
        if (sameYear && sameMonth) {
          if (currentDate === t.getDate()) {
            return "";
          } else if ((currentDate - 1) === t.getDate()) {
            return "昨天";
          } else if ( (currentDate - 2) === t.getDate() ) {
            return "前天";
          } else {
            return tf(t.getDate()) + '日';
          }
        } else {
          return tf(t.getDate()) + '日';
        }
      case 'HH':
        return tf(t.getHours());
      case 'mm':
        return tf(t.getMinutes())
      case 'ss':
        return tf(t.getSeconds())
    }
  })
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页