gpt4 book ai didi

iphone - 如何改进此“DateFromNextWeekDay:FromDate”方法代码?

转载 作者:行者123 更新时间:2023-12-01 19:28:05 25 4
gpt4 key购买 nike

很高兴听到有关如何改进/缩短此方法的建议。简而言之,需要:

  • 查找星期几(例如星期三)与传递给该方法的内容匹配的下一个日期。
  • 例如,给定日期(包括该给定日期)的下一个WED

    下面的代码:
    - (NSDate*)DateFromNextWeekDay:(NSInteger)weekDay FromDate:(NSDate*)fromDate {
    // Returns the next week day, as specified by "weekDay", from the specified "fromDate"
    NSDate *fromDateMidday = [[NSDate date] dateBySettingHour:12 andMinute:0];
    NSDate *dateCounter = [[fromDateMidday copy] dateByAddingTimeInterval:-86400]; // Take 1 day away, which will get incremented in the loop
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger day;
    do{
    dateCounter = [dateCounter dateByAddingTimeInterval:86400];
    unsigned units = NSWeekdayCalendarUnit;
    NSDateComponents *components = [gregorian components:units fromDate:dateCounter];
    day = [components weekday];
    } while(day != weekDay);
    [gregorian release];
    return dateCounter;
    }

    谢谢

  • 最佳答案

    您可以找到传入日期的星期几,从目标星期几中减去该日期,最后将该结果添加到传入日期中。无需遍历日期。因此它将是:

    daysToAdd =(targetDayOfWeek-currentDayDayOfWeek)%7

    修改减法的原因是要处理目标日期小于当前日期的情况(例如,星期六,您正在寻找星期二)。

    关于iphone - 如何改进此“DateFromNextWeekDay:FromDate”方法代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5372425/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com