zl程序教程

您现在的位置是:首页 >  其他

当前栏目

vue.js客服系统实时聊天项目开发(十三)日期缩短展示,同一天只展示时秒,同一年展示月日小时秒

2023-03-07 09:42:41 时间

客服系统中在展示聊天消息时间的时候,根据当前日期与目标日期的情况进行缩短显示,如果是同一天,只显示小时、分钟、秒,如果是同一年,只显示月日小时、分钟、秒,否则显示全部,根据这样的缩短逻辑就可以进行显示了。

具体实现函数

//缩短时间
function shortTime(t){
    let time=new Date(t);
    let today = new Date();
    let todayYear = today.getFullYear();
    let todayMonth = today.getMonth()+1;
    let todayDate = today.getDate();

    let targetYear = time.getFullYear();
    let targetMonth = time.getMonth()+1;
    let targetDate = time.getDate();
    let targetHour = time.getHours();
    let targetMinutes = time.getMinutes();
    let targetSeconds = time.getSeconds();
    // 同一天,只显示小时、分钟、秒
    if (todayYear === targetYear && todayMonth === targetMonth && todayDate === targetDate) {
        if (targetHour < 10) {
            targetHour = "0" + targetHour;
        }
        if (targetMinutes < 10) {
            targetMinutes = "0" + targetMinutes;
        }
        if (targetSeconds < 10) {
            targetSeconds = "0" + targetSeconds;
        }
        return targetHour + ":" + targetMinutes + ":" + targetSeconds;
    }
    // 同一年,只显示月日等
    if (todayYear === targetYear) {

        if (targetMonth < 10) {
            targetMonth = "0" + targetMonth;
        }
        if (targetDate < 10) {
            targetDate = "0" + targetDate;
        }
        if (targetHour < 10) {
            targetHour = "0" + targetHour;
        }
        if (targetMinutes < 10) {
            targetMinutes = "0" + targetMinutes;
        }
        if (targetSeconds < 10) {
            targetSeconds = "0" + targetSeconds;
        }
        return `${targetMonth}-${targetDate} `+targetHour + ":" + targetMinutes + ":" + targetSeconds;
    }
    return t;
}
  1. 首先定义了一个 shortTime 函数,接收一个时间戳字符串 t
  2. 然后通过 new Date(t) 将字符串转化为时间对象,方便后面的操作。
  3. 接着通过获取当前时间的方法判断 t 与当前时间是否在同一天,如果是,只显示小时,分钟,秒。如果不是,判断是否在同一年,如果是,只显示月日等。
  4. 在判断完成后,给时间按照要求进行格式化,并返回。
  5. 如果不是同一天也不是同一年,则直接返回传入的时间戳字符串。