0
我創建了一個簡單的函數來獲取一天中的第一天和最後一天。 看着NSLog輸出,我發現不同的值是從同一日期的NSDate描述符和組件日返回的,爲什麼?同一日期的NSDate和NSDateComponent值之間的差異
這裏的NSLog輸出:
NSDATE: 2011-04-03 22:00:00 +0000, DAY COMPONENT: 4
NSDATE: 2011-04-09 22:00:00 +0000, DAY COMPONENT: 10
正如你可以看到,是的NSDate 4月3日和一天組分是4對第一行,並分別9和10爲第二個。
下面的代碼:
NSDate *date = [NSDate date]; //Today is April 5th 2011
NSCalendar *cal =[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
[cal setFirstWeekday:2]; //My week starts from Monday
//DEFINE BEGINNING OF THE WEEK
NSDate *beginningOfWeek = nil;
[cal rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:nil forDate:date];
NSDateComponents *beginComponents = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:beginningOfWeek];
//DEFINE END OF THE WEEK, WITH 6 days OFFSET FROM BEGINNING
NSDateComponents *offset = [[NSDateComponents alloc]init];
[offset setDay:6];
NSDate *endOfWeek = [cal dateByAddingComponents:offset toDate:beginningOfWeek options:0];
NSDateComponents *endComponents = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:endOfWeek];
NSLog(@"NSDATE: %@, DAY COMPONENT: %d",beginningOfWeek, [beginComponents day]);
NSLog(@"NSDATE: %@, DAY COMPONENT: %d",endOfWeek, [endComponents day]);
我得到當前的日期輸出,我看到這是前進2小時。 在我啓動功能我的時鐘是在19:16的日期,看看這裏輸出:「今天2011-04-05 17:16:20 +0000」是17.16而不是19.16。 在我的問題中,我看到輸出結果是2小時也報告22:00而不是24:00(因此,正確的一天) – MatterGoal 2011-04-05 17:22:53