js仿照聊天记录的时间显示 今天 昨天

来源:互联网 发布:出售淘宝旗舰店id 编辑:程序博客网 时间:2024/06/05 19:53
    var time = '2017年06月02日 10:43:24';    // 时间统一函数    function getTimeText(argument) {        var timeS = argument;        var todayT = ''; //        var yestodayT = '';        var timeCha = getTimeS(timeS);        timeS = timeS.slice(-8);        todayT = new Date().getHours()*60*60*1000 + new Date().getMinutes()*60*1000 + new Date().getSeconds()*1000;        yestodayT = todayT + 24*60*60*1000;        if(timeCha > yestodayT) {            return argument.slice(0,11);        }        if(timeCha > todayT && timeCha < yestodayT) {            return timeS.slice(0,2)>12?'昨天 下午'+(timeS.slice(0,2)==12 ? 12 : timeS.slice(0,2) - 12)+timeS.slice(2,5):'昨天 上午'+timeS.slice(0,5);        }        if(timeCha < todayT) {            return timeS.slice(0,2)>=12?'下午'+(timeS.slice(0,2)==12 ? 12 : timeS.slice(0,2) - 12)+timeS.slice(2,5):'上午'+timeS.slice(0,5);        }            }// 时间戳获取    function getTimeS(argument) {        var timeS = argument;        timeS = timeS.replace(/[年月]/g,'/').replace(/[日]/,'');        return new Date().getTime() - new Date(timeS).getTime() - 1000; //有一秒的误差    }    var timeText = getTimeText(time);    console.log(time+'应该显示为   '+timeText)    </script>

实际效果图:


结束语:由于时间的原因,小编没有继续写下去,只是简单地写了些,如果一周的时间内显示星期几,只需要继续写一个时间变量=yestoday+一周的毫秒数,下面判断就可以了,但必须注意的是时间格式必须是'2017年06月02日 10:43:24';谢谢大家查看

阅读全文
0 0
原创粉丝点击