在objective-c中获取一周的第一天和最后一天

时间:2015-10-11 10:23:48

标签: objective-c nsdate locale nsdateformatter nsdatecomponents

我希望在本周的第一天获得每个人的特定区域设置。 例如,美国周开始于星期日和周一其他国家。

我想在星期一开始为大家开始,这是因为我想将它用于SQLQuery。

我有这个:

NSDate *weekDay = [NSDate date]; //any date in the week in which to calculate the first or last weekday   
 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:weekDay];
[components setDay:([components day]-([components weekday]-[[NSCalendar currentCalendar] firstWeekday]))];

NSDate *firstWeekday = [gregorian dateFromComponents:components];
NSDate *lastWeekday = [[gregorian dateFromComponents:components] dateByAddingTimeInterval:7 * 24 * 3600 - 1];
NSLog(@"first - %@ \nlast - %@", firstWeekday, lastWeekday);

如果您的语言环境周从星期一开始,但是如果从星期日开始并不能返回我想要的内容,那么哪个工作正常。

所以想象今天是2015年10月11日 周日地区将返回第11周的第一天,即最后一天,17 星期一语言环境将返回第5周的第一天,即最后一天11

我想在我的应用执行的任何地方返回第二个选项。

感谢。 最好的问候。

1 个答案:

答案 0 :(得分:7)

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

cal.firstWeekday = 2;// set first week day to Monday
// 1: Sunday, 2: Monday, ..., 7:Saturday

NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSCalendarUnitWeekOfYear
       startDate:&startOfTheWeek
        interval:&interval
         forDate:now];
//startOfTheWeek holds the beginning of the week

endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval - 1];
// endOfWeek now holds the last second of the last week day

[cal rangeOfUnit:NSCalendarUnitDay
       startDate:&endOfWeek
        interval:NULL
         forDate:endOfWeek];
// endOfWeek now holds the beginning of the last week day

测试:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterShortStyle;

NSLog(@"start: %@", [formatter stringFromDate:startOfTheWeek]);
NSLog(@"end:   %@", [formatter stringFromDate:endOfWeek]);

打印

start: 12.10.15, 00:00
end:   18.10.15, 00:00

所以周一是本周的开始

如果我设置

cal.firstWeekday = 1;

它会打印

start: 11.10.15, 00:00
end:   17.10.15, 00:00

星期日是一周的第一天