NSCalendar return wrong date for previous Monday in first week of next year

时间:2016-10-20 13:12:10

标签: ios objective-c

I am using below code to calculate previous Monday using random date. Which work file but my code break on next year date.below is the code for same :

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1483620311.228];
NSLog(@"current date ===> : %@", date);

NSCalendar *calendar;
calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]];
NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"Australia/Sydney"];
[calendar setTimeZone:zone];

NSDateComponents *nowComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone fromDate:date];
if (nowComponents.weekday == 1) {    //If my date fall in sunday then I am moving to previous week.
    [nowComponents setWeekOfYear:[nowComponents weekOfYear]-1];
}

[nowComponents setWeekday:2]; //Monday

NSDate *previousMonday = [calendar dateFromComponents:nowComponents];
NSLog(@"previousMonday date ===> : %@", previousMonday);

In Log I am getting as :

current date ===> : 2017-01-05 12:45:11 +0000
previousMonday date ===> : 2018-01-01 12:45:11 +0000

I have seen other stack overflow resource but not getting expected solution.

1 个答案:

答案 0 :(得分:1)

使用nextDateAfterDate的{​​{1}}可以更明智地实现这一目标。在这种情况下,它可以向后搜索单个组件的匹配NSCalendar

NSCalendarUnitWeekday == 2

时区和区域设置并不重要。