美文网首页
格式化时间的两种思路

格式化时间的两种思路

作者: 皇甫圣坤 | 来源:发表于2019-03-19 19:08 被阅读0次

    formatDate () {
          // 获取当前时间 - this.comment.date 
          const time = Math.floor((this.now - this.comment.date) / 1000) // 秒
          const arr = ['年前', '月前', '天前', '小时前', '分钟前', '秒前']
          const narr = [31536000, 2592000, 86400, 3600, 60, 1]
          
          for (let i = 0; i<narr.length; i++) {
            const flag = Math.floor(time / narr[i])
            console.log(flag)

            if (flag > 0) 
              return flag + arr[i]
            }
          }
          return 1 + '秒前'
        }

    formatTime() {
            const d = new Date(this.topic.last_reply_at);
            //生成日期对象
            const time = new Date(this.topic.last_reply_at).getTime();
            //根据time获取事件戳
            const t = Math.floor((Date.now() - time) / 1000);
            return t < 60
              ? t + "秒前"
              : t / 60 < 60
              ? Math.floor(t / 60) + "分钟前"
              : t / 60 / 60 < 24
              ? Math.floor(t / 60 / 60) + "小时前"
              : t / 3600 / 24 < 30
              ? Math.floor(t / 3600 / 24) + "天前"
              : d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate();
          }

相关文章

网友评论

      本文标题:格式化时间的两种思路

      本文链接:https://www.haomeiwen.com/subject/kwwnmqtx.html