날짜 형식이있는 nsstring의 덩어리로 nsstring을 변환
-
20-09-2019 - |
문제
이것은 간단 할 수 있습니다. 아직 찾지 못했습니다.
nsstring @"20100216190205"를 "yyyy-mm-dd hh : mm : ss"형식의 nsstring으로 어떻게 변환합니까?
IE : @"2010-02-16 19:02:05"
편집하다:다른 상황에서는 nsdateformatter를 더 일반적으로 사용하지 않기를 원했습니다.
해결책
순전히 서면 코드 연습으로 :
NSString* digits = @"20100216190205"; // this is probably a parameter somewhere
NSMutableString* formatted = [digits mutableCopy];
[formatted insertString:@":" atIndex:12];
[formatted insertString:@":" atIndex:10];
[formatted insertString:@" " atIndex:8];
[formatted insertString:@"-" atIndex:6];
[formatted insertString:@"-" atIndex:4];
NSLog(@"original string: %@ -> formatted: %@", digits, formatted);
그러나 나는 동의한다 : 자신을 쉽게 가고,이를 위해 Date Formatter를 사용하십시오.
다른 팁
각 서브 스트링을 추출하여 정수로 변환 할 수 있습니다 (-intValue
), 그런 다음 사용하십시오 NSDateComponents
이것들을 날짜로 변환합니다. 그리고 nsdateformatter를 사용하는 것보다 훨씬 더 번거 롭습니다.
귀하의 경우 NSDateFormatter의 형식을 설정해야합니다. yyyyMMddHHmmss
전화하기 전에 -dateFromString:
, 즉
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [formatter dateFromString:@"20100216190205"];
....
당신은 당신을 설정해야합니다 formatter
예제에있는 문자열을 구문 분석하기 위해 yyyymmddhhmmss의 형식. 새로운 포피터를 만들거나 원래 Formatter의 형식을 수정하여 원하는 더 매력적인 형식을 통합해야합니다 (@"yyyy-MM-dd HH:mm:ss"
).
제휴하지 않습니다 StackOverflow