2011-03-21 3 views
3

Objective-C에서 어떻게 상대 날짜를 얻을 수 있습니까?상대 날짜를 얻는 방법

"오늘"이있는 경우 "어제", "지난 주", "지난 2 주", "한 달 전", "두 달 전"을 어떻게 찾습니까?

+0

정말 무엇을 요구하고 있는지 확실하지 않습니다. –

답변

10

따라서 NSDate *today = [NSDate date];이있는 경우 NSDateComponents을 사용하여 상대 날짜를 얻을 수 있습니다.

NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDate *today = [NSDate date]; 

NSDateComponents *yesterdayComponents = [[NSDateComponents alloc] init]; 
[yesterdayComponents setDay:-1]; 
NSDate *yesterday = [calendar dateByAddingComponents:yesterdayComponents toDate:today options:0]; 
[yesterdayComponents release]; 

NSDateComponents *twoWeeksAgoComponents = [[NSDateComponents alloc] init]; 
[twoWeeksAgoComponents setWeek:-2]; 
NSDate *twoWeeksAgo = [calendar dateByAddingComponents:twoWeeksAgoComponents toDate:today options:0]; 
[twoWeeksAgoComponents release]; 

NSDateComponentsNSCalendar 핸들 언더 플로와 (당신이 options: 비트와 그것을 해제하지 않는 한) 자동으로 넘쳐. 따라서 오늘이 "28 February"이고 "내일"을 원하면 연도에 따라 자동으로 "29 February"또는 "1 March"을 선택합니다. 그것은 꽤 멋지다. 이것은을 수행하는 유일한 올바른 방법 인 입니다.

+0

주 수가 올바르게 반환되지 않습니다. \t NSDateComponents * TwoWeeksAgoComponents = [구성 요소 복사]; \t [TwoWeeksAgoComponents setWeek : [TwoWeeksAgoComponents week] -2]; \t NSDate * TwoWeeksAgo = [calendar dateFromComponents : TwoWeeksAgoComponents]; \t NSLog ([formatter stringFromDate : TwoWeeksAgo]); \t [TwoWeeksAgoComponents release]; – Ali

+0

또한 NSCalendar는 ipad 캘린더에 의존합니다. 또는 항상 georgean입니다. – Ali

+0

이 코드는 작동하지 않습니다. 항상 초기 날짜를 반환합니다. 나는'dateByAddingComponents : toDate : options :'를 사용해야 만했다. 나는이 답변에 대한 모든 upvotes가 실제로 코드를 테스트하지 않은 사람들로부터 왔다고 가정합니다. – titaniumdecoy

관련 문제