js插件--获取指定时间距离当前时间状态:上周,当前周,前天,昨天,今天,明天,后天,当前周,下周。

3,266 阅读3分钟
function getTimeStatus(date) {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const inputDate = new Date(date);
  const inputYear = inputDate.getFullYear();
  const inputMonth = inputDate.getMonth();
  const inputDay = inputDate.getDate();
  const dayDiff = Math.floor((today - inputDate) / 86400000); // 86400000毫秒 = 1天

  // 计算相对于当前周的偏移量
  const dayOfWeek = inputDate.getDay();
  const currentDayOfWeek = now.getDay();
  const weekDiff = dayDiff + (dayOfWeek < currentDayOfWeek ? 7 : 0);

  if (weekDiff < 0) {
    if (dayDiff === -1) return '前天';
    if (dayDiff === -2) return '大前天';
    return '上周';
  } else if (weekDiff > 0) {
    if (dayDiff === 1) return '明天';
    if (dayDiff === 2) return '后天';
    return '下周';
  } else { // weekDiff === 0
    if (dayDiff === 0) {
      const hoursDiff = now.getHours() - inputDate.getHours();
      if (hoursDiff < 24) {
        if (hoursDiff < 12) return '今天';
        return '当前周';
      }
    }
    if (dayDiff === -1) return '昨天';
    if (dayDiff === 1) return '明天';
    return '当前周';
  }
}

// 使用示例
console.log(getTimeStatus(new Date())); // 今天
console.log(getTimeStatus(new Date(Date.now() - 86400000))); // 昨天
console.log(getTimeStatus(new Date(Date.now() + 86400000))); // 明天