我的函数遇到了问题,该函数应该检索本周的星期一日期。
有时放假一天:
+(NSDate *) lastMondayBeforeDate:(NSDate*)timeStamp {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps =
[gregorian components:NSWeekdayCalendarUnit fromDate:timeStamp];
NSInteger weekday = [comps weekday];
weekday = weekday==1 ? 6 : weekday-2;
NSTimeInterval secondsSinceMondayMidnight =
(NSUInteger) [timeStamp timeIntervalSince1970] % 60*60*24 +
weekday * 60*60*24;
NSLog(@"MONDAY's DATE-----------%@", [timeStamp dateByAddingTimeInterval:-secondsSinceMondayMidnight]);
return [timeStamp dateByAddingTimeInterval:-secondsSinceMondayMidnight];
}发布于 2012-04-11 14:29:32
苹果有code demonstrating how to do almost exactly this。它们的目标是一周中的周日,而不是周一,但您可以在适当的位置添加1进行调整。
你肯定不想做像60*60*24和计算秒这样的事情来调整。例如,由于夏令时的更改,几天的时间可能长于或少于24小时。
https://stackoverflow.com/questions/10091495
复制相似问题