views:

264

answers:

3

This might be simple. I have searched, not found yet.

How do I convert the NSString @"20100216190205" to an NSString of format @"yyyy-MM-dd HH:mm:ss".

ie: @"2010-02-16 19:02:05"

EDIT: I wanted to avoid using the NSDateFormatter to be more generic, for other situations.

+2  A: 

You can extract each substring, convert them into integers (-intValue), then use NSDateComponents to convert these into a date. And it is much more troublesome than using NSDateFormatter.

In your case, the NSDateFormatter's format needs to be set to yyyyMMddHHmmss before calling -dateFromString:, i.e.

[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [formatter dateFromString:@"20100216190205"];
....
KennyTM
Thanks. I got it. I was supposed to use:[formatter setDateFormat:@"yyyyMMddHHmmss"];
erastusnjuki
+1  A: 

You'll need to set your formatter's format to yyyyMMddHHmmss to parse the string you have in your example. You'll need to either create a new formatter or modify the original formatter's format to incorporate the more visually appealing one that you want (@"yyyy-MM-dd HH:mm:ss").

Malaxeur
+1  A: 

Purely as an exercise in writing code:

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);

But I agree: go easy on yourself, and use a date formatter for this.

Sixten Otto
For learning sakes, This was really helpful :)
erastusnjuki