【网页前端】JS呈现时间戳为与当前时间比较结果

1、时间戳显示

经常可以看到论坛或者新闻上,时间戳为刚刚,xx分钟前,xx小时前等字样,前端如何实现呢?

image

2、时间戳实现

这个功能比较简单,直接上函数,time_str是时间戳的字符串结果,转换成Date对象,

Date对象可以获取年月日等信息,new一个Date表示当前时间,相关信息进行比较之后,定制返回结果即可。

//时间处理函数,多少分钟前,多少小时前,超过24小时显示日期,超过一年显示年月日
        getTimeShow:function(time_str){
            //debugger;
            var now = new Date();
            var date = new Date(time_str);
            //计算时间间隔,单位为分钟
            var inter = parseInt((now.getTime() - date.getTime())/1000/60);
            if(inter == 0){
                return "刚刚";
            }
            //多少分钟前
            else if(inter < 60){
                return inter.toString() + "分钟前";
            }
            //多少小时前
            else if(inter < 60*24){
                return parseInt(inter/60).toString() + "小时前";
            }
            //本年度内,日期不同,取日期+时间  格式如  06-13 22:11
            else if(now.getFullYear() == date.getFullYear()){
                return (date.getMonth()+1).toString() + "-" +
                    date.getDate().toString() + " " +
                    date.getHours() + ":" +
                    date.getMinutes();
            }
            else{
                return date.getFullYear().toString().substring(2, 3) + "-" +
                (date.getMonth()+1).toString() + "-" +
                date.getDate().toString() + " " +
                date.getHours() + ":" +
                date.getMinutes();
            }
        },

3、实现效果

image

好记性不如烂笔头
原文地址:https://www.cnblogs.com/inns/p/5586358.html