5

How would I convert @"20090302" to @"2009/03/02" or to @"02/03/2009"?

I found the solution and this is the update

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"YYYYMMDD"];



NSDate *date = [formatter dateFromString:yourinoutstring];


[formatter setDateFormat:@"DD/MM/YYYY"];

NSString *outDate = [formatter stringFromDate:date];
Ali
  • 1,975
  • 5
  • 36
  • 55
  • Answered duplicate: http://stackoverflow.com/questions/1353081/nsstring-to-nsdate – Blender Mar 20 '11 at 13:51
  • I need the output to be nsstring too – Ali Mar 20 '11 at 13:54
  • 2
    Then convert `NSString -> NSDate -> NSString`. What are you using the date for? – Blender Mar 20 '11 at 13:54
  • I just want to formate the nsstring @"20100304" to @"04/02/2010" for displaying purpose – Ali Mar 20 '11 at 13:56
  • 2
    I disagree that the linked question also answers this one. Therefore, I have edited this question (particularly the title) to clarify it and provided an answer. – jscs Mar 20 '11 at 19:18

1 Answers1

7

You will want to use an NSDateFormatter for this purpose.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"YourDateInputFormat"];

Where you can figure out what @"YourDateInputFormat" should be by reading the Data Formatting Guide, Date Formatters chapter. You get an NSDate from that:

NSDate *date = [formatter dateFromString:yourString];

Then change the formatter's format to give the output you want:

[formatter setDateFormat:@"YourDateOutputFormat];

Then you can convert that date and get the string you want:

NSString *outString = [formatter stringFromDate:date];
jscs
  • 63,694
  • 13
  • 151
  • 195
  • thanks your answer helped me , but it's outdated code I use ios 4.2 – Ali Mar 21 '11 at 08:32
  • `-initWithDateFormat:allowNaturalLanguage:` is only for pre-10.4 formatter behavior. You need to use `-init` and `-setDateFormat:` separately. – Dave DeLong Mar 21 '11 at 17:19
  • @Dave: thanks for pointing that out. Sorry, Ali. I've edited my answer. – jscs Mar 21 '11 at 18:09