如何在不同的时区(EST& IST)找到下周日

时间:2017-03-07 08:13:58

标签: ios objective-c timezone nsdate

我必须从设备的当前日期找到下一个星期日的日期(NSDate)。

我使用了以下逻辑:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self];
NSUInteger weekdayToday = [components weekday];

NSInteger daysToMonday = (8 - weekdayToday) % 7;

NSDate *weekEndPrev = [self dateByAddingTimeInterval:60*60*24*daysToMonday];

在美国东部时间,如果时间接近晚上11点,我将在星期一作为周末。

让我知道可行的解决方案。我尝试了很多选择。 Nothings适用于2个不同的时区。

先谢谢。

4 个答案:

答案 0 :(得分:0)

您只需要获得所需的天数,然后将它们添加到当前日期:

    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate * newDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:value toDate:date options:0];

其中value - 是要添加的天数

答案 1 :(得分:0)

首先查找当前星期日星期日,然后使用NSDateComponents添加7天。

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:today];
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:(0 - ([weekdayComponents weekday] - 1))];
NSDate *sudayCurWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:7];
NSDate *nextSunday = [gregorian dateByAddingComponents:offsetComponents toDate:sudayCurWeek options:0];
NSLog(@"%@",nextSunday);

答案 2 :(得分:0)

您可以在没有任何数学的情况下执行此操作,最好留给NSCalendar,因为它可以处理夏令时等。首先,您需要一个具有正确时区的日历。例如IST:

NSCalendar *gc = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
gc.timeZone = [NSTimeZone timeZoneWithName:@"IST"];

然后您可以使用nextDateAfterDate:matchingUnit:value:options:在给定时间后查找下一个星期日的开始。例如:

NSDate *start = ... // the time you wish to start from
NSDate *nextSunday =
    [gc nextDateAfterDate:start
                 matching:UnitNSCalendarUnitWeekday // match based on weekday number
                    value:1                         // Sunday = weekday 1
                  options:NSCalendarMatchNextTime   // read the docs!
    ];

返回的日期nextSunday将是日历时区gc的00:00的下一个星期日。

HTH

答案 3 :(得分:0)

最后,我得到了解决方案..

NSDateComponents *components = [[NSCalendar currentCalendar] componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"] fromDate:[NSDate date]]; // Pass date for which you want to find next Sunday
NSUInteger weekdayToday = [components weekday];
NSInteger daysToMonday = (8 - weekdayToday) % 7;
NSDate *weekEndPrev = [[NSDate date] dateByAddingTimeInterval:60*60*24*daysToMonday];