문제

내가 작업중 인 코코아 앱에 반복 이벤트를 추가하고 있습니다. 수학적으로 (3600*24*7 = 1 주)를 정의 할 수 있기 때문에 매일과 주에 잘 반복됩니다. 다음 코드를 사용하여 날짜를 수정합니다.

[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))]

이벤트가 반복 된 이후 몇 달이 지났는지 알고 있지만 미래에 1 개월/3 개월/6 개월/9 개월을 나타내는 NSDate 객체를 만드는 방법을 알 수 없습니다. 이상적으로는 사용자가 10 월 14 일부터 월별로 반복한다고 말하기를 원하며 매월 14 일을 반복 할 것입니다.

도움이 되었습니까?

해결책

(거의 동일합니다 이 질문.)

로부터 선적 서류 비치:

nscalendardate의 사용은 강력하게 낙담했습니다. 아직 더 이상 사용되지 않았지만 Mac OS X V10.5 이후 다음 주요 OS 릴리스에있을 수 있습니다. 캘린더 계산을 위해서는 달력에 설명 된대로 NSCALENDAR, NSDATE 및 NSDATECOMPONENTS의 적절한 조합을 사용해야합니다. 코코아의 날짜 및 시간 프로그래밍 주제.

그 조언에 따라 :

NSDate *today = [NSDate date];

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

NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];

NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];

NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];

nextMonthComponents.day = todayDayComponents.day;
NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];

[gregorian release];

보다 직접적이거나 효율적인 구현이있을 수 있지만 이는 정확해야하며 올바른 방향을 가리켜 야합니다.

다른 팁

nscalender, nsdatecomponents 및 nsdate를 사용하십시오.

NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
components.month = 1;
NSDate *oneMonthFromNow = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:[NSDate date] options:0];

다른 속성을 설정하십시오 components 다른 기간을 얻기 위해 (예 : 3 개월, 6 개월 등).

참고 : 상황에 따라 사용하고 싶을 수도 있습니다. [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease] 대신에 [NSCalendar currentCalendar], "1 개월"이라면 그레고리 달력에서 1 개월을 의미합니다. "

아마 nscalendardate를 사용할 것입니다.

현재 날짜의 주간, 월간 및 연도를 세 숫자로 얻으십시오.

필요한 달 (1/3/6/9)을 추가하고, 1) 그 날짜가 존재하는지 (예 : 4 월 31 일, 2 월 29 일, 29 년 2 월 29 일), 2) 연도의 롤오버를 추가하십시오.

Nscalendardate의 Initwithyear : Month : Day : Hour : Minute : Second : TimeZone으로 새 날짜를 만들었습니다.

nscalendardate 더 이상 New SDK에 의해 지원되지 않으며 배포를위한 구축 중에 문제가 있습니다.

아래를 좋아할 수 있습니다.

NSDate *today = [NSDate date];

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

NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];

NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:nextMonth];
NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];

[gregorian release]; 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top