实际项目中一些简单时间函数的封装:

2019-12-05  本文已影响0人  尤雨溪的大迷弟

1.计算剩余时间,需求:可用于商品的倒计时等:

        restTime(time){
            var setTime = new Date(time);
            var nowTime = new Date();
            var restSec = setTime.getTime() - nowTime.getTime();
            if(restSec < 0){
                return false;
            }
            var day = parseInt(restSec / (60*60*24*1000));
            var hour = parseInt(restSec / (60*60*1000) % 24);
            var minu = parseInt(restSec / (60*1000) % 60);
            var sec = parseInt(restSec / 1000 % 60);
            var str = "剩余"+day+"天"+hour+"时"+minu+"分"+sec+"秒";
            return str;
        },

举个栗子:

    let result = this.restTime("2030/11/11 11:11");
    console.log(result); // 剩余3993天19时56分54秒

2.计算传入时间过了多久,需求:可用于记录留言的时间(是什么时候留的)等:

    SmartDate(originDate) {
      originDate = new Date(originDate);
      let nowDate = new Date(),
      isToday = false, // 传入时间是否是当天
      isYesterday = false,
      isPastYear = false,
      isPreviousYear = false,
      originYear,
      originMonth,
      originDay,
      diffMinute, // 传入时间和当前时间相差的分钟数
      formatedDate;

      diffMinute = Math.round((nowDate.getTime() - originDate.getTime()) / (1000 * 60));
      originYear = originDate.getFullYear();
      originMonth = originDate.getMonth() + 1;
      originDay = originDate.getDate();

      // 相差的分钟数 <= 当前时间的分钟数,即传入时间不是当天
      if (diffMinute <= nowDate.getHours() * 60) {
      isToday = true;
      }
      if (nowDate.getDate() - originDay == 1) {
      isYesterday = true;
      }
      if (nowDate.getFullYear() - originYear == 1) {
      isPreviousYear = true;
      } else if (nowDate.getFullYear() - originYear > 1) {
      isPastYear = true;
      }
      // 以下可以自己定义区间
      if (diffMinute <= 0) { // 一般留言的需求,diffMinute都大于0
      formatedDate = '你在未来';
      }else if (diffMinute < 10 && isToday) { // 当相差的分钟数 < 10且isToday为true
      formatedDate = '刚刚';
      } else if (diffMinute < 60 && isToday) { // 当10 < 相差的分钟数 < 60且isToday为true
      formatedDate = `${diffMinute}分钟前`;
      } else if (diffMinute < 60 * 24 && isToday) { // 当60 < 相差的分钟数 < 60*24且isToday为true
      formatedDate = `${Math.floor(diffMinute / 60)}小时前`;
      } else if (diffMinute < 60 * 24 * 2 && isYesterday) { // 当60*24 < 相差的分钟数 < 60*24*2且isYesterday为true
      formatedDate = '1天前';
      } else if (diffMinute < 60 * 24 * 4) { // 当60*24*2 < 相差的分钟数 < 60*24*4
      formatedDate = '2天前';
      } else if (isPreviousYear) {
      formatedDate = '去年';
      } else if (isPastYear) {
      formatedDate = `${originYear}年`;
      } else {
      formatedDate = `${originMonth}月${originDay}日`;
      }
      return formatedDate;
    }, 

举个栗子:

    let result = this.SmartDate("2019/12/5 15:33");
    console.log(result); // 11分钟前
    result = this.SmartDate("2050/12/5 15:33");
    console.log(result); // 你在未来
    result = this.SmartDate("2019/12/4 15:33");
    console.log(result); // 1天前
上一篇下一篇

猜你喜欢

热点阅读