代码之家  ›  专栏  ›  技术社区  ›  Sergino

如何使用日期fns查找一周中最近的一天

  •  0
  • Sergino  · 技术社区  · 7 年前

    我希望能够根据当前日期和日期fns找出过去一周中最近的一天。假设我需要根据当前日期查找过去最近的星期五、星期三、星期四等。

    我查阅了文档,只能看到这两种方法 https://date-fns.org/docs/closestTo https://date-fns.org/v1.29.0/docs/getDay 我想这可能会有帮助,但我要找的那个不见了。

    有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  9
  •   Ray Chan    4 年前

    // use require or import in your code
    // const { getISODay, addDays } = require("date-fns");
    const { getISODay, addDays } = dateFns;
    
    function getDayInPast(dayOfWeek, fromDate = new Date()) {
      // follow the getISODay format (7 for Sunday, 1 for Monday)
      const dayOfWeekMap = {
        Mon: 1,
        Tue: 2,
        Wed: 3,
        Thur: 4,
        Fri: 5,
        Sat: 6,
        Sun: 7,
      };
    
      // dayOfWeekMap[dayOfWeek] get the ISODay for the desired dayOfWeek
      const targetISODay = dayOfWeekMap[dayOfWeek];
      const fromISODay = getISODay(fromDate);
    
      // targetISODay >= fromISODay means we need to trace back to last week
      // e.g. target is Wed(3), from is Tue(2)
      // hence, need to -7 the account for the offset of a week
      const offsetDays =
        targetISODay >= fromISODay
          ? -7 + (targetISODay - fromISODay)
          : targetISODay - fromISODay;
    
      return addDays(fromDate, offsetDays);
    }
    
    console.log(getDayInPast("Mon"));
    console.log(getDayInPast("Tue"));
    console.log(getDayInPast("Wed"));
    console.log(getDayInPast("Thur"));
    console.log(getDayInPast("Fri"));
    console.log(getDayInPast("Sat"));
    console.log(getDayInPast("Sun"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>

    感谢@giraff在上一版本中指出有关偏移的问题

        2
  •  0
  •   giraff    4 年前
    const { getISODay, addDays } = require('date-fns');
    
    function getClosestDayOfLastWeek(dayOfWeek, fromDate = new Date()) {
        // follow the getISODay format (7 for Sunday, 1 for Monday)
        const dayOfWeekMap = {
            Mon: 1,
            Tue: 2,
            Wed: 3,
            Thur: 4,
            Fri: 5,
            Sat: 6,
            Sun: 7,
        };
    
        // -7 means last week
        // dayOfWeekMap[dayOfWeek] get the ISODay for the desired dayOfWeek
    
        // e.g. If today is Sunday, getISODay(fromDate) will returns 7
        // if the day we want to find is Thursday(4), apart from subtracting one week(-7),
        // we also need to account for the days between Sunday(7) and Thursday(4)
        // Hence we need to also subtract (getISODay(fromDate) - dayOfWeekMap[dayOfWeek])
        let offsetDays = - (getISODay(fromDate) - dayOfWeekMap[dayOfWeek]);
        if (offsetDays > 0) offsetDays -= 7;
    
        return addDays(fromDate, offsetDays);
    }
    
    console.log(getClosestDayOfLastWeek('Mon'));