JS获取指定日期和当前日期关系(前天,昨天,今天,明天,后天)

项目中用到ts,如不需要请手动删除相关代码
/**
 * 获取当前日期零点的时间戳
 * @param date
 */
function getStartTimestampOfDay(date: Date): number {
  try {
    return new Date(
      date.toISOString().replace(/\d{2}:\d{2}:\d{2}\.\d{3}/g, "00:00:00.000")
    ).getTime();
  } catch (e) {}

  return 0;
}

/**
 *
 * @param date
 */
function getWeekDayMappingOfCurrent(
  date: Date
): {
  [key: number]: string;
} {
  const current = getStartTimestampOfDay(date);
  if (current) {
    return {
      [current - 2 * 86400000]: "前天",
      [current - 1 * 86400000]: "昨天",
      [current]: "今天",
      [current + 1 * 86400000]: "明天",
      [current + 2 * 86400000]: "后天"
    };
  }
  return {};
}


/**
 * 获取格式化的周几:前天、昨天、今天、明天、后天
 * @param date
 */
function getWeekDayString(date: Date, current: Date): string {
  const timestamp = getStartTimestampOfDay(date);
  const mapping = getWeekDayMappingOfCurrent(current);

  return mapping[timestamp];
}

使用方法如下图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37793545/article/details/104699949