You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Golang筛选输出日期区间内指定星期几的日期

Solution to Filter Specific Weekdays in Date Range

Let's adjust your code to only output the dates that match your target weekday (like Monday or Tuesday) within the start/end date range. The key is to calculate the first matching date in the range and then increment by 7 days each time (since weekdays repeat weekly) instead of iterating every single day.

Modified Code

func GetSchedule(c *gin.Context) {
    response := ResponseControllerList{}
    selected_day := "Monday"
    conditions := bson.M{"day": selected_day}

    data, err := models.GetSchedulingListing(conditions)
    if err != nil {
        // Handle database retrieval error early
        response = ResponseControllerList{
            config.FailureCode,
            config.FailureFlag,
            config.FailureMsg,
            nil,
            nil,
        }
        GetResponseList(c, response)
        return
    }

    // Map weekday strings to Go's time.Weekday constants for easy comparison
    weekdayMap := map[string]time.Weekday{
        "Sunday":    time.Sunday,
        "Monday":    time.Monday,
        "Tuesday":   time.Tuesday,
        "Wednesday": time.Wednesday,
        "Thursday":  time.Thursday,
        "Friday":    time.Friday,
        "Saturday":  time.Saturday,
    }

    targetWeekday, ok := weekdayMap[selected_day]
    if !ok {
        // Handle invalid weekday input
        response = ResponseControllerList{
            config.FailureCode,
            config.FailureFlag,
            "Invalid weekday specified",
            nil,
            nil,
        }
        GetResponseList(c, response)
        return
    }

    for _, item := range data {
        start_date := item.StartDate
        end_date := item.EndDate
        start_time := item.StartTime
        end_time := item.EndTime

        start_working_hours := time.Unix(start_time, 0).Format("3:04PM")
        end_working_hours := time.Unix(end_time, 0).Format("3:04PM")

        // Convert Unix timestamps to time.Time objects for easier date manipulation
        currentDate := time.Unix(start_date, 0)
        endDate := time.Unix(end_date, 0)

        // Calculate days needed to jump to the first occurrence of the target weekday
        daysToAdd := (int(targetWeekday) - int(currentDate.Weekday()) + 7) % 7
        currentDate = currentDate.AddDate(0, 0, daysToAdd)

        // Iterate weekly, outputting each matching weekday until we exceed the end date
        for !currentDate.After(endDate) {
            fmt.Println(currentDate.Format("Monday, 01-02-2006") + " " + start_working_hours + " " + end_working_hours)
            currentDate = currentDate.AddDate(0, 0, 7)
        }
    }

    dataCount, err := models.GetRecordsCount(config.ScheduleCollection, conditions)
    if err != nil {
        response = ResponseControllerList{
            config.FailureCode,
            config.FailureFlag,
            config.FailureMsg,
            nil,
            nil,
        }
    } else {
        response = ResponseControllerList{
            config.SuccessFlag,
            config.SuccessFlag,
            config.SuccessMsg,
            data[0],
            dataCount,
        }
    }

    GetResponseList(c, response)
}

Key Changes Explained

  • Weekday Mapping: We created a weekdayMap to convert human-readable weekday strings (like "Monday") to Go's built-in time.Weekday enum, which simplifies date comparison logic.
  • Jump to First Matching Date: Instead of checking every single day, we calculate the exact number of days needed to reach the first target weekday from the start date. The +7 and %7 ensures we handle cases where the start date falls after the target weekday (e.g., start is Tuesday, target is Monday—we add 6 days to reach the next Monday).
  • Efficient Weekly Iteration: Once we have the first matching date, we increment by 7 days each cycle (since weekdays repeat weekly) until we pass the end date. This is way more efficient than looping through every day, especially for large date ranges.
  • Robust Error Handling: Added early checks for database retrieval failures and invalid weekday inputs to make the code more reliable.

Example Output

If selected_day is "Monday" and your date range starts on Tuesday, 05-01-2018, the output will skip to the first Monday in the range (05-07-2018) and then list every subsequent Monday until the end date matches your desired result.

内容的提问来源于stack exchange,提问作者user9684058

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:07:46