NSCalendar dateFromComponents:给出意想不到的结果

时间:2015-04-10 04:38:35

标签: ios objective-c nsdate nsdateformatter nscalendar

我尝试编写一个以NSDate作为输入的方法,并返回该日期所在的第一天。我一直在使用NSDateComponents来尝试设置年份,星期和星期几;但我得到了意外的行为。例如:

NSDateComponents* comps = [[NSDateComponents alloc]init];
[comps setYear:2015];
[comps setWeekday:1];
[comps setWeekOfYear:1];
NSLog(@"%@\n%@\n\n", comps, [formatter stringFromDate:[calendar dateFromComponents:comps]]);

结果:

<NSDateComponents: 0x7fbc24cc9870>
Calendar Year: 2015
Week of Year: 1
Weekday: 1
Dec 27 2016

除了所有的陌生感,这是我的方法,它应该从NSDate返回一周的第一天:

- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate
{
    // Use the user's current calendar and time zone
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [calendar setTimeZone:timeZone];
    NSDateComponents *dateComps = [calendar components:NSCalendarUnitYear | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday fromDate:inputDate];
    NSDateComponents* startOfWeek = [[NSDateComponents alloc]init];
    // Set the time components manually
    [startOfWeek setWeekOfYear:dateComps.weekOfYear];
    [startOfWeek setYear:dateComps.year];
    [startOfWeek setWeekday:0];
    // Convert to date
    NSDate *beginningOfDay = [calendar dateFromComponents:startOfWeek];
    return beginningOfDay;
}

1 个答案:

答案 0 :(得分:0)