zoukankan      html  css  js  c++  java
  • x秒前

    /**
     * 格式化时间,1秒前,1分钟前 今天 10:11 昨天 10:11 9月11日 10:10
     * @param {Date} date 时间对象
     * @param {Date} currentDate 对比时间
     * @return {String} 格式化后的时间内容
     */
    var shortTime = function(date, currentDate) {
        var now = currentDate,
            // 今日秒数
            todaySec = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds(),
            secDiff = Math.floor( (now.getTime() - date.getTime()) / 1000 );
        if(secDiff < 60) {
            secDiff = secDiff < 1 ? 1 : secDiff;
            return parseInt(secDiff) + '秒前';
        }
        if(secDiff <= 3600) {
            return parseInt(secDiff / 60) + "分钟之前";
        }
        var h = ("0" + date.getHours()).slice(-2),
            m = ("0" + date.getMinutes()).slice(-2), 
            d = date.getDate();
        return ( now.getDate() == d && secDiff < 86400 ) ?  ( "今天 " + h + ":" + m ) : 
               ( secDiff >= todaySec && ( secDiff <= 86400 + todaySec ) ) ? ( "昨天 " + h + ":" + m ) :
               ( (date.getMonth() + 1) + "月" + d + "日 " +  h + ":" + m );
    };
    
    //但一般我们会拿到一个"xxxx-xx-xx xx:xx:xx"的"发布时间",要相对当前时间格式化
    var shortTime = function(date, currentDate) {
        var pubtimeThis = date.split(" ");
        var temp_a = pubtimeThis[0].split("-");
        var temp_b = pubtimeThis[1].split(":");
        date = new Date(temp_a[0], temp_a[1] - 1, temp_a[2], temp_b[0], temp_b[1]);
    
        var now = currentDate || (new Date()),
            // 今日秒数
            todaySec = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds(),
            secDiff = Math.floor( (now.getTime() - date.getTime()) / 1000 );
        if(secDiff < 60) {
            secDiff = secDiff < 1 ? 1 : secDiff;
            return parseInt(secDiff) + '秒前';
        }
        if(secDiff <= 3600) {
            return parseInt(secDiff / 60) + "分钟之前";
        }
        var h = ("0" + date.getHours()).slice(-2),
            m = ("0" + date.getMinutes()).slice(-2), 
            d = date.getDate();
        return  ( now.getDate() == d && secDiff < 86400 ) ?  ( "今天 " + h + ":" + m ) :
                ( secDiff >= todaySec && ( secDiff <= 86400 + todaySec ) ) ?  ( "昨天 " + h + ":" + m ) : 
                ( (date.getMonth() + 1) + "月" + d + "日 " +  h + ":" + m );
    };
    

      

  • 相关阅读:
    Linux记录-批量安装zabbix(转载)
    k8s-基础环境配置(六)
    k8s记录-ntpd时间同步配置(五)
    k8s记录-flanneld+docker网络部署(四)
    Java面试通关要点汇总集
    Java并发编程系列
    码农需要知道的“潜规则”
    领域驱动设计文章
    自动化测试的一些思考
    轻量级爬虫框架
  • 原文地址:https://www.cnblogs.com/frostbelt/p/2990615.html
Copyright © 2011-2022 走看看