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

具体实现函数

//缩短时间

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;

}

首先定义了一个 shortTime 函数,接收一个时间戳字符串 t。

然后通过 new Date(t) 将字符串转化为时间对象,方便后面的操作。

接着通过获取当前时间的方法判断 t 与当前时间是否在同一天,如果是,只显示小时,分钟,秒。如果不是,判断是否在同一年,如果是,只显示月日等。

在判断完成后,给时间按照要求进行格式化,并返回。

如果不是同一天也不是同一年,则直接返回传入的时间戳字符串。

唯一在线客服系统

https://gofly.v1kf.com

查看原文