微信聊天日期转换
* IOS 时间 有bug需要兼容: '2022-12-12' ==> '2022/12/12'
* 每周的第一天是 周天~
/**获取当月第几周 */
function getMonthWeek(Date){
let theSaturday = Date.getDate() + (6 - Date.getDay());
return Math.ceil(theSaturday / 7);
}
/** 判断iOS*/
const isiOS = ()=>{
const u = navigator.userAgent;
let iOs = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
return iOs;
};
/**阿拉伯数字 星期数转中文 */
function SectionToChinese(traget) {
console.log(traget);
let result = ''
switch(traget) {
case 0:
result = '天'
break;
case 1:
result = '一'
break;
case 2:
result = '二'
break;
case 3:
result = '三'
break;
case 4:
result = '四'
break;
case 5:
result = '五'
break;
case 6:
result = '六'
break;
}
return result;
}
/**个位数转换两位数 */
function twoNumber(number) {
return Number(number) < 10 ? `0${number}` : number;
}
/**日期格式 */
const fromCurrentTime = (target) => {
let tempTraget = target;
/**兼容IOS */
if(isiOS()) tempTraget = tempTraget.replace(/-/g, '/');
/**目标 */
let tragetDate = new Date(tempTraget);
const tragetYear = tragetDate.getFullYear(); /**目标年 */
const tragetMonth = tragetDate.getMonth() + 1; /**目标月 */
const tragetDay = tragetDate.getDate() ; /**目标日 */
const tragetHours = tragetDate.getHours() ; /**目标时 */
const tragetMinutes = tragetDate.getMinutes(); /**目标分 */
/**当前 */
let currentDate = new Date() /**当前日期 */
const currentYear = currentDate.getFullYear(); /**当前年 */
const currentMonth = currentDate.getMonth() + 1; /**当前月 */
const currentDay = currentDate.getDate(); /**当前日 */
const currentHours = currentDate.getHours() ; /**当前时 */
// const currentMinutes = currentDate.getMinutes(); /**当前分 */
let resultDate;
/**比较年份 */
if(tragetYear < currentYear) { /**不同年 */
resultDate = `${tragetYear}年${tragetMonth}月${tragetDay}日`
} else {
/**同年比较月份 */
if(tragetMonth < currentMonth) { /**同年不同月 */
resultDate = `${tragetMonth}月${tragetDay}日 ${twoNumber(tragetHours)}:${twoNumber(tragetMinutes)}`
} else {
/**同月比较周 */
if(getMonthWeek(tragetDate) !== getMonthWeek(currentDate)) { /**同月份不同周 */
// if(Math.abs(getMonthWeek(tragetDate) - getMonthWeek(currentDate)) === 1) {
resultDate = `${tragetMonth}月${tragetDay}日 ${twoNumber(tragetHours)}:${twoNumber(tragetMinutes)}`
// }
} else {
/**同周比较差几天 */
if(tragetDay === currentDay) { /**同周同天 */
/**同天比较小时 */
if(Math.abs(currentHours - tragetHours) === 0) { /**1h内 */
resultDate = `刚刚`
} else {
resultDate = `${twoNumber(tragetHours)}:${twoNumber(tragetMinutes)}`
}
} else if(Math.abs(currentDay - tragetDay) === 1) { /**同周差一天 */
resultDate = `昨天 ${twoNumber(tragetHours)}:${twoNumber(tragetMinutes)}`
} else {
resultDate = `星期${SectionToChinese(tragetDate.getDay())} ${twoNumber(tragetHours)}:${twoNumber(tragetMinutes)}`
}
}
}
}
return resultDate;
}
const time = fromCurrentTime ('2022-04-02 18:18:00')
console.log(time)