修改bug时,碰到一个需求,签到功能时间需要为连续的,显示相应文案,后端返回的数据格式是时间戳,先把时间戳转为普通时间格式,然后去除时分秒毫秒,然后遍历,直接po代码
//判断签到时间是否为连续时间
continueDays() {
let days: any = [];
//this.selectedLeanth是后端返回的数组对象,里面每条对象有对应的时间戳数据
this.selectedLeanth.map((item: any) => {
let r = item.createTime;
r = Foundation.dateFormat(r);//封装的将时间戳转为普通时间数据的方法
days.push(r);
});
//然后遍历这个数组
let db = days.sort().map((d: any, i: any) => {
let dt = new Date(d);
dt.setDate(dt.getDate() + 4 - i); // 处理为相同日期
// 去除时、分、秒、毫秒
dt.setHours(0);
dt.setMinutes(0);
dt.setSeconds(0);
dt.setMilliseconds(0);
return +dt;
});
let ret = true;
db.forEach((d: any) => {
if (db[0] !== d) {
ret = false;
}
});
//当ret为true时,代表时间是连续的,反之不连续
if (ret) {
this.signtxt = `已连续签到${this.selectedLeanth.length}天,继续加油`;
} else {
this.signtxt = "已签到一天";
}
}
我的代码比较复杂,因为是把时间戳转为普通格式,然后遍历了好几遍,实现思路是看了这篇博客
https://www.52cik.com/2016/07/10/consecutive-dates.html,大家可以去看看,讲解的更详细