2014-01-22 3 views
-1

내 앱에서 시작일과 종료일을 설정하려고합니다. 종료일은 시작일로부터 1 개월이어야합니다.NSDate에 한 달 추가

내가 찾고 결과를 얻을 수있는 방법이 있나요

start date = 1st January 2014 
end date = 31st January 2014 

은 현재 내가 시작 날짜 1 개월을 추가하려면 다음 방법을 사용하고 있지만, 종료 날짜는

dateByAddingComponents:toDate:options: 

2014 년 2 월 1 일이된다 종료일은 항상 시작일로부터 1 개월 - 1 일이 될 것입니다.

나는 이것이 의미가 있기를 바랍니다.

감사합니다.

+0

2014 년 1 월 31 일의 예상 출력은 얼마입니까? 2 월 30 일입니까? 아니면 2 월 28 일입니까? –

+0

두 개의 별도 dateByAddingComponents 연산을 수행 할 것으로 생각합니다. 첫 번째 연산은 월을 더하고, 두 번째는 하루를 뺍니다. –

+0

@isoyaboy이 질문에 대한 도움이 필요하십니까? – Tariq

답변

1

물론 :

- (NSDate *)lastDayOfMonthDateForDate:(NSDate *)date { 
    NSDateComponents *comp = [NSDateComponents new]; 
    comp.day = -1; 
    comp.month = 1; 

    return [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0]; 
} 
+0

나는 2014 년 3 월 31 일에 결과를 2014 년 4 월 30 일로 예상하는 입력으로 방금 귀하의 방법을 시도했지만 결과는 내 결과입니다. 시작일 : 2014-03-30 23:00:00 +0000 종료일 : 2014-04-28 23:00:00 +0000. 어떤 이유로 dateFromComponents가 내 입력을 2014 년 3 월 30 일로 변경했는데 그 이유는 확실하지 않지만 종료일은 2014 년 3 월 30 일에도 여전히 올바르지 않습니다. –

+0

나는 다음 달에만 제공해야한다고 생각합니다. –

+0

@isoyaboy 제 대답을 확인하십시오. –

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

NSDateComponents *dateComp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]]; 

NSLog(@"Input Date: %@",[NSDate date]); 

[dateComp setDay:dateComp.day - 1]; 

[dateComp setMonth:dateComp.month + 1]; 

NSDate *nextMonthMinusOneday = [gregorian dateFromComponents:dateComp]; 

NSLog(@"Output date %@",nextMonthMinusOneday); 

출력 : 예상대로 나는 위의 코드와 그 작동을 확인했습니다

Input Date: 2014-03-31 21:21:34 +0000 
Output date 2014-04-30 05:00:00 +0000 
+0

모든 도움에 감사드립니다. 불행히도 나는 그 달의 마지막 날을 찾고 있지 않다. 주어진 날짜로부터 1 개월 - 1 일인 날짜를 찾고있다. –

+0

아 .. 알았어. 나는 나의 대답을 편집했다. 2014 년 3 월 31 일에 확인한 결과 2014 년 4 월 30 일입니다. –

+0

@isoyaboy : 출력 로그를 확인하십시오. –

0
- (NSDate *)dateForNextMonthMinusSingleDay:(NSDate *)date { 
    NSDateComponents *dayOffsetComponents = [[NSDateComponents alloc] init]; 
    [dayOffsetComponents setMonth:1]; 
    [dayOffsetComponents setDay:-1]; 
    return [[NSCalendar currentCalendar] dateByAddingComponents:dayOffsetComponents 
                 toDate:date 
                 options:0]; 
} 


- (NSDate *)dateFromMMDDYYYYString:(NSString *)string { 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; 
    [formatter setDateFormat:@"MM/dd/yyyy"]; 
    return [formatter dateFromString:string]; 
} 


NSDate *date = [self dateForNextMonthMinusSingleDay:[self dateFromMMDDYYYYString:@"01/01/2014"]]; 

.