zoukankan      html  css  js  c++  java
  • 优雅的格式化时间显示

    在像评论列表这样的前端页面中,经常会出现时间的字段,如果显示一个标准的yyyy-MM-dd HH:mm:ss这样的时间格式,显然不是很友好,通常产品会要求显示 [1分钟前]、[刚刚] 类似的文字,那么怎么用js实现呢?我这里封装了一个通用的函数以实现,贴出完整代码:

    //时间格式化
    function getDateDiff(date){
    
        if(typeof date === 'string'){
            date = new Date(Date.parse(date.replace(/-/g, "/")));
        }else if(typeof date === 'object'){
            date = date.getTime();
        }
    
        var result = '',
            differentValue = new Date().getTime() - date;
    
        if(differentValue < 0) {
            return '穿越时空'
        }
    
        var minute = 1000 * 60,
            hour = minute * 60,
            day = hour * 24,
            week = day * 7,
            month = day * 30,//且都用30天算
            year = month * 12;
    
        if(differentValue / year >= 1){
            result = parseInt(differentValue / year) + "年前"
        }else if(differentValue / month >= 1){
            result = parseInt(differentValue / month) + "月前"
        }else if(differentValue / week >= 1){
            result = parseInt(differentValue / week) + "周前"
        }else if(differentValue / day >= 1){
            result = parseInt(differentValue / day) + "天前"
        }else if(differentValue / hour >= 1){
            result = parseInt(differentValue / hour) + "小时前"
        }else if(differentValue / minute >= 1){
            result = parseInt(differentValue / minute) + "分钟前"
        }else{
            result = "刚刚";  
        }
    
        return result;
    }
    
    console.log(getDateDiff('2017-06-21 20:16:24'))
    console.log(getDateDiff(parseInt('1497183384000')))
    console.log(getDateDiff(1497183384000))
    console.log(getDateDiff(new Date('2011-01-11 20:16:24')))
    console.log(getDateDiff(new Date('2017-07-14 11:43:24')))
    console.log(getDateDiff(new Date('2017-07-14 20:16:24')))
    

    控制台输出如图

  • 相关阅读:
    Delphi数据库处理
    cxgrid的FINDPANEL编程
    LESS简介
    LESS速查
    $(window).load(function() {})和$(document).ready(function(){})的区别
    CSS中单位px和em,rem的区别
    父元素与子元素之间的margin-top问题
    CSS垂直居中精华总结
    Font Awesome使用指南
    Sublime3安装过程及常用插件安装及常用快捷键
  • 原文地址:https://www.cnblogs.com/liliangel/p/7170091.html
Copyright © 2011-2022 走看看