我该如何改进这个“DateFromNextWeekDay:FromDate”方法代码?
很高兴听到有关如何改进/缩短此方法的建议。简而言之,需要:
- 找到与传递到方法中的日期相匹配的下一个日期(例如星期三)。
- 例如,给定日期的下一个周三(包括给定日期)
代码如下:
- (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;
}
谢谢
Would be happy to hear of suggestions re how to improve / shorten this method. In short needing to:
- Find the next date for which it's day of week (e.g. Wed) matches what is passed into the method.
- For example the next WED from a given date (and including that given date)
Code Below:
- (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;
}
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需找到传入日期的星期几,从目标星期几中减去该日期,最后将该结果添加到传入的日期中即可。无需循环遍历日期。所以它是:
daysToAdd = ( targetDayOfWeek - currentDayDayOfWeek ) % 7
修改减法的原因是为了处理目标日期小于当前日期的情况(例如,它是星期六,而您正在寻找星期二) 。
You could just find the day of the week of the passed in date, subtract that from the target day of the week, and finally add that result to the date passed in. No need to loop through the dates. So it would be:
daysToAdd = ( targetDayOfWeek - currentDayDayOfWeek ) % 7
The reason for moding the subtraction is to handle the cases where the target day is smaller than the current day (it is a saturday and you are looking for a tuesday for example).