2016-08-09 2 views
2

시간표를 만드는 앱을 만들고 있습니다. 매주 새해를 만들 수 있습니다. 앱로드가 완료되면 현재 주를로드해야합니다 (예 : 1 월 1 일이면 1 주째를 표시해야 함). NSDateFormatter를 사용하여 현재 주를 확인합니다. NSDateFormatterNSDateFormatter 및 NSDateComponents가 주 번호에 대해 다른 값을 반환합니다.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"ww"]; 

int currentWeek = [[time stringFromDate:[NSDate date]] intValue]; 

내가 그렇게 일하는 내가 NSLog를 사용하는지 확인하고 싶어 (I 8 월 2016 9 일에이 테스트되었다).

32을 반환했습니다.

NSDateComponents

그래서 NSDateFormatter는 현재 주 32입니다 생각합니다. 여태까지는 그런대로 잘됐다. 앱이 사용자에게 특정 기간이 시작될 것이라고 알리는 푸시 알림을 보내야합니다. 따라서 앱은 NSDateComponents를 사용하여 알림을 예약합니다.

// Setting the notification's fire date. 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
NSDateComponents *dateComps = [[NSDateComponents alloc] init]; 
[dateComps setWeekday:3]; // Because it's on a Tuesday 
[dateComps setWeekOfYear:currentWeek]; // 32 
[dateComps setYear:2016]; 
[dateComps setHour:12]; 
[dateComps setMinute:20]; 
NSDate *theFireDate = [calendar dateFromComponents:dateComps]; 

// Creates the notification. 
UILocalNotification *Alert = [[UILocalNotification alloc] init]; 
Alert.timeZone = [NSTimeZone defaultTimeZone]; 
Alert.alertBody = @"This is a message!"; 
Alert.fireDate = theFireDate; 
[[UIApplication sharedApplication] scheduleLocalNotification:Alert]; 

그리고 NSLog도 사용했습니다.

NSLog(@"%@", theFireDate); 

그러나 2016-08-02 12:20:00 +0000은 현재 날짜가 아닙니다. 실제로는 현재 날짜에서 7 일 또는 1 주일 전의 날짜입니다. 그렇다면 현재 주는 32 대신 실제로 33입니다. 즉 NSDateFormatter가 잘못되었음을 의미합니까? 아니면 실제로는 NSDateComponents가 잘못되었음을 의미하는 32입니다. 그리고 그 둘 사이의 차이점은 무엇입니까?

+1

로케일과 시간대를 날짜 포맷터로 설정 한 다음 다시 디버그하십시오. –

+1

왜 그런지 물어 보지 말고,'NSCalendar * calendar = [NSCalendar currentCalendar]'를 사용하면 작동합니다 (그레고리력을 가지고 있습니다). 그러나 alloc/init으로 인해 같은 문제가 발생합니다. 어딘가 설정을 놓치고있는 것 같습니다. '[setLocale : [NSLocale currentLocale]];을 설정하면 작동합니다. – Larme

+1

시간대, 로캘 및 캘린더가 일치하지 않는 것 같습니다. – Michael

답변

2

NSDateFormatter을 사용하지 말고 NSCalendar을 사용하면 훨씬 정확합니다.

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
NSInteger weekOfYear = [calendar component:NSCalendarUnitWeekOfYear fromDate:[NSDate date]]; 
관련 문제