2015-01-21 3 views
-1

날짜 문자열에서 시간을 가져 오려고합니다. 다음 문자열은 오전 12시를 반환합니다. 이 로그 문에 도달 할 때문자열에서 변환 할 때 NSDate가 nil을 반환합니다.

2010-08-24 0시 0분 0초 0000

그러나 다음 코드를 사용하여 내있는 NSDate 객체은 nil을 반환합니다. 여기서 문제는 무엇입니까? 감사!

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"h:mma"]; 
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"]; 
NSLog(@"DATE: %@", [date description]); 

출력 : 날짜 : (널)

+0

그것의 당신의 통과가 날짜 형식과 일치 doen't 날짜 형식 (문자열) .... 같은 날짜 형식을 사용하려고하기 때문에 ... [문자열에서있는 NSDate 만들]의 –

+0

가능한 중복 (http://stackoverflow.com/questions/9769190/create-a-nsdate-from-a-string) –

+1

왜 아무도 설명서를 참조하지 ?? –

답변

1

이 하나를 시도

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"YYYY-MM-dd hh:mm:ss ZZZZ"]; 
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"]; 
NSLog(@"DATE: %@", [date description]); 

건배!

는 playgorund에서 테스트 :

enter image description here

+0

감사합니다.하지만 어떻게 시간을 반환 할 수 있습니까? – Pheepster

+0

[NSDate date]; // 오늘 날짜를 반환합니다. – D33pN16h7

+1

위의 날짜 형식이 잘못되었습니다. –

0

그럼 당신은 주어진 형식으로 날짜 문자열에서

하지 1.Get있는 NSDate 객체를 시간을 추출하기 위해 다음과 같은 절차를 사용할 수 있습니다.

2. 필요한 형식으로 NSDateFormatter 객체를 설정하십시오.

3. 날짜 문자열을 필수 형식으로 가져옵니다.

- (BOOL)application:(UIApplication *) 
application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
    NSString *date = [self convertDate:@"2010-08-24 00:00:00 +0000" 
          fromFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ" 
           toFormat:@"hh:mm a"]; 

    NSLog(@"DATE: %@", [date description]); 

    return YES; 
} 


- (NSString *)convertDate:(NSString *)inDateString 
      fromFormat:(NSString *)fromFormat 
       toFormat:(NSString *)toFormat 
{ 
    NSDateFormatter *dateFormatter = nil; 
    NSString *outDateString = nil; 
    NSDate *date = nil; 

    dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:fromFormat]; 

    date = [dateFormatter dateFromString:inDateString]; 

    [dateFormatter setDateFormat:toFormat]; 
    outDateString = [dateFormatter stringFromDate:date]; 

    return outDateString; 
} 
+0

날짜 형식이 잘못되었습니다 (다른 형식과 달리 정확하지는 않음). –

관련 문제