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

时间的格式的封装

程序员文章站 2022-07-13 11:54:09
...

第三章

在开发中,我们经常会遇到对于时间的进行封装

这个我不得不提一下微信小程序中自带封装, 不得不说, 写的很好, 值得我学习

工整, 美观, (或许这就是代码之美吧)

  • 格式化:
const formatTime = date => {
    date = new Date(date)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

时间的格式的封装
感觉这个更加是无敌
与上面这个效果是一样的

let d = new Date();
d.toJSON().substr(0,10)+' '+d.toTimeString().substr(0,8)

当然除了substr()字符串方法, 也有substring(), 与slice(), 方法, (slice 与在字符串与数组中均可使用)

  • 另一种方法

join(’-’), 既可以用在数组中, 也可以用在字符串中

const formatDate = date => {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month; //通过字符串的长度判断
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}
  • 倒计时:
// 倒计时处理
const getOverTime = time => {
    let a = new Date(time).getTime();
    let c = a - Date.now();
    if (c <= 0) {
        return false
    }
    let days = Math.floor(c / (24 * 3600 * 1000));
    let leave1 = c % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000));
    let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000));
    let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    let seconds = Math.round(leave3 / 1000);
    return days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
}
  • 判断时间
    这个写的不是很好, 应该可以理由高阶函数在对这个进行简化
function getDateDiff(dateTimeStamp) {
  const minute = 1000 * 60;
  const hour = minute * 60;
  const day = hour * 24;
  const month = day * 30;
  const year = day * 365;
  const now = new Date().getTime();
  const diffValue = now - dateTimeStamp;
  if(diffValue < 0){
   
      return '数据出错';
  }

  const yearC = diffValue / year;
  const monthC = diffValue / month;
  const weekC = diffValue / (7 * day);
  const dayC = diffValue / day;
  const hourC = diffValue / hour;
  const minC = diffValue / minute;
  let result = '';



  if(yearC >= 1){
      result = parseInt(yearC) + '年以前';
  }else if(monthC >= 1){
      result = parseInt(monthC) + '个月前';
  }else if(weekC >= 1){
      result = parseInt(weekC) + '星期前';
  }else if(dayC >= 1){
      result = parseInt(dayC) + '天前';
  }else if(hourC >= 1){
      result = parseInt(hourC) + '小时前';
  }else if(minC >= 5){
      result = parseInt(minC) + '分钟前';
  }else{
      result = '刚刚发表';
  }
  return result;
}