js 时间各种展示总结(n天前,时间格式化)

js时间格式化

传入什么格式,就输出什么格式,默认{y}-{m}-{d} {h}:{i}:{s},你可以传{y}/{m}/{d} {h}:{i}:{s},也可以{y}年{m}月{d}日,传你需要的年月日时分秒和间隔符,是不是很好用,对了还有星期几,例如{y}-{m}-{d} {h}:{i}:{s} 星期{a}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

刚刚、n分钟前、n小时前,n天前

几种一样,看自己需求

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}
export function dateDiff(timestamp) {
  // 补全为13位
  let arrTimestamp = (timestamp + '').split('');
  for (let start = 0; start < 13; start++) {
    if (!arrTimestamp[start]) {
      arrTimestamp[start] = '0';
    }
  }
  timestamp = arrTimestamp.join('') * 1;

  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let week = day * 7;
  let now = new Date().getTime();
  let year = new Date().getFullYear(); // 获取当前时间年份
  let createYear = new Date(timestamp).getFullYear(); // 获取指定时间戳年份
  let diffValue = now - timestamp;
  let yearsDiff = year - createYear; // 获取年份差

  // 如果本地时间反而小于变量时间
  if (diffValue < 0) {
    return '刚刚';
  }

  // 计算差异时间的量级
  let weekC = diffValue / week; // 相对于7天
  let dayC = diffValue / day; // 相对于24小时
  let hourC = diffValue / hour; // 相对于1小时
  let minC = diffValue / minute; // 相对于1分钟

  // 数值补0方法
  let zero = function (value) {
    if (value < 10) {
      return '0' + value;
    }
    return value;
  };

  // 使用
  if (minC < 5) {
    return "刚刚";
  } else if (minC < 59) {
    return Math.ceil(minC) + "分钟前";
  } else if (hourC < 23) {
    return Math.ceil(hourC) + "小时前";
  } else if (weekC < 1) {
    return Math.ceil(dayC) + "天前";
  } else if (weekC > 1) {
    return (function () {
      let date = new Date(timestamp);
      if (yearsDiff >= 1) {
        return date.getFullYear() + '/' + zero(date.getMonth() + 1) + '/' + zero(date.getDate());
      } else {
        return zero(date.getMonth() + 1) + '/' + zero(date.getDate());
      }
    })();
  }
}
// 微信公众号发布时间那截取的
(function(){
    if (window.__second_open__) return; 
    var first_js_time = +new Date();
    var showDate="";
    var svrDate=new Date("1544749949"*1000);
    var createDate=new Date("1544745600"*1000);
    var ct="1544745600"*1;
    var publish_time = "2018-12-14" || "";
    var cD={
      year:createDate.getYear(),
      month:createDate.getMonth()+1,
      date:createDate.getDate()
    };
    svrDate.setHours(0);
    svrDate.setMinutes(0);
    svrDate.setSeconds(0);
    var todayDate=svrDate.getTime()/1000;
    svrDate.setDate(1);
    svrDate.setMonth(0);
    var yearDate=svrDate.getTime()/1000;
    
    if(ct>=todayDate){
      showDate="今天";
    
    }else if(ct>=todayDate-60*60*24){
       showDate="昨天";
    
    }else if(ct>=todayDate-2*60*60*24){
      showDate="前天";
    }else if(ct>=todayDate-3*60*60*24){
      showDate="3天前";
    }else if(ct>=todayDate-4*60*60*24){
      showDate="4天前";
    }else if(ct>=todayDate-5*60*60*24){
      showDate="5天前";
    }else if(ct>=todayDate-6*60*60*24){
      showDate="6天前";
    }else if(ct>=todayDate-2*7*60*60*24){
      showDate="1周前";
    }else if(ct>=yearDate){
      var tmp = publish_time.split('-');
      showDate = parseInt(tmp[1]) + '月' + parseInt(tmp[2]) + '日';
       }else{
      showDate=publish_time;
    };
    if(document.getElementById("publish_time")){
      document.getElementById("publish_time").innerText=showDate;
    }
})();

判断时间段,白天黑夜

export function parseTimeSlot() {
  let now = new Date(),
    hour = now.getHours()
  if (hour < 6) {
    return ("凌晨好!")
  } else if (hour < 9) {
    return ("早上好!")
  } else if (hour < 12) {
    return ("上午好!")
  } else if (hour < 14) {
    return ("中午好!")
  } else if (hour < 17) {
    return ("下午好!")
  } else if (hour < 19) {
    return ("傍晚好!")
  } else if (hour < 22) {
    return ("晚上好!")
  } else {
    return ("夜里好!")
  }
}
export function isNight () {
  let now = new Date(),
    hour = now.getHours()
  if (hour >= 7 && hour < 19) {
    return false
  } else if (hour < 7 || hour >= 19) {
    return true
  }
}

判断冬夏秋冬

export function parseSeason() {
  let now = new Date(),
    month = (now.getMonth()) + 1
  if (month >= 3 && month <= 5) {
    return 'spring'
  } else if (month >= 6 && month <= 8) {
    return 'summer'
  } else if (month >= 9 && month <= 11) {
    return 'autumn'
  } else if (month = 12 || month <= 3) {
    return 'winter'
  }
 }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值