iOS请勿打扰导致此错误的错误?

时间:2013-01-07 20:21:14

标签: objective-c ios nsdate nsdatecomponents

我试图找出最近的“请勿打扰”错误(Ars Technica link)是否影响了我的代码。我试图获取上周一午夜的日期和时间戳。由于我是在星期一写这篇文章的,所以我希望今天(2013年1月7日)到期,但我是2013年1月4日。

我正在关注guide posted by Apple,但我想修改它以找到上周一,而不是周日。

+(NSTimeInterval)StartOfWeekMonday {
    NSTimeInterval finalTime = -1;

    NSInteger weekday;

    NSDate *monday  = 0;

    NSCalendar *greg = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *weekdays = [greg components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
    NSDateComponents *subtract = [[NSDateComponents alloc] init];
    NSDateComponents *final    = 0;

    weekday = ( weekdays.weekday == 1 ) ? 6 : weekdays.weekday;

    [subtract setDay:(0 - weekday - 1)];

    monday = [greg dateByAddingComponents:subtract toDate:[NSDate date] options:0];
    final  = [greg components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:monday];
    monday = [greg dateFromComponents:final];

#ifdef DEBUG
    NSLog( @"%s - %d -> Weekday: %d", __FILE__, __LINE__, weekday );
    NSLog( @"%s - %d -> Monday: %@", __FILE__, __LINE__, [monday descriptionWithLocale:[NSLocale currentLocale]] );
#endif

    finalTime = [monday timeIntervalSince1970];


    return finalTime;
}

我的注销在下面,工作日是正确的(我在星期一写这个),但日期显然是错误的,它应该是Monday: Monday, January 7, 2013, 12:00 AM

2013-01-07 15:07:33.792 MY-APP[5524:14c03] Weekday: 2
2013-01-07 15:07:36.757 MY-APP[5524:14c03] Monday: Friday, January 4, 2013, 12:00:00 AM Eastern Standard Time

现在正在模拟器中,但我所有的其他日期计算都给出了预期值。

我是否有可能受到最近的“请勿打扰”的影响,并且必须等到明天(2013年1月8日)才能看到预期的结果,或者我错过了一些完全不同的东西?

1 个答案:

答案 0 :(得分:1)

问题在于如何计算减法。要么我完全不理解Apple提供的示例,要么就是不够清楚。计算减法的解决方案如下:

weekday = ( weekdays.weekday == 1 ) ? 8 : weekdays.weekday;
toSubtract = ( 2 - weekday );

[subtract setDay:toSubtract];

运行各种测试产生了正确的"星期一。"最后,这与影响请勿打扰的日期错误无关。