zoukankan      html  css  js  c++  java
  • 小程序实现微信朋友圈时间显示效果

    小程序实现微信朋友圈时间显示效果:

    1分钟前,2分钟前,···,59分钟前,1小时前,2小时前,···,23小时前,一天前,2天前,2019-06-21 等等...

    相关代码如下:getTime() {    let start = '2019-6-21 22:41:00'    let nowTime = new Date()

        let oldTime = new Date(start)
        let diff = Math.floor((nowTime - oldTime)/1000/60)
        let time = start
        
        if(diff <= 59){
            time = diff + '分钟前'
        }else if(diff <= 60*24-1){
            time = Math.floor(diff / 60) + '小时前'
        }else if(diff <= 60*24*3-1){
            time = Math.floor(diff / 60 / 24) + '天前'
        }else{
            time = time.split(" ")[0]  
        }
        return time
    }

    实际开发过程中,会发现后台返回的数据不可能一直是 yyyy-mm-dd hh:ii:ss 格式的

    也可能返回的是时间戳,这个时候会报  time.split 不是一个方法

    解决方法:将时间戳或者 yyyy-mm-dd hh:ii:ss 格式 都通过js的Dete对象转换,代码如下:

    getTime() {
        let start = '2019-6-21 22:41:00'
        let nowTime = new Date()
        let oldTime = new Date(start)
        let diff = Math.floor((nowTime - oldTime) / 1000 / 60)
        let time = start
        if (diff <= 59) {
            time = diff + '分钟前'
        } else if (diff <= 60 * 24 - 1) {
            time = Math.floor(diff / 60) + '小时前'
        } else if (diff <= 60 * 24 * 3 - 1) {
            time = Math.floor(diff / 60 / 24) + '天前'
        } else {
            // time = time.split(" ")[0]   // startTime格式:yyyy-mm-dd hh:ii:ss
            time = this.getNowFormatDate(time)
        }
        return time
    }
    getNowFormatDate(time) {
        let date = new Date(time);
        let seperator1 = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        let currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }

    开发中因为不确定后台传回的是什么样的格式,因此在刚开始添加全局替换

    ios不支持 “yyyy-mm-dd”,那么就替换成 “yyyy/mm/dd”

    let reg=new RegExp("-");
    if(reg.test(startTime)){
        startTime = startTime.replace(/-/g, '/')
    }
  • 相关阅读:
    PHP 输出图像
    js 获取元素
    js 获取 坐标
    【javascript】ajax 基础 --本文转载
    JS获取当前时间
    如何安装win10和linux 双系统
    自动验证是ThinkPHP
    thinkphp 动态验证码 ------控制器传输到html 数据时间转换处理
    thinkphp 验证
    软件测试-测试开发需要学习的知识结构
  • 原文地址:https://www.cnblogs.com/cap-rq/p/11080125.html
Copyright © 2011-2022 走看看