Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-format NSString representing a date

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];
like image 609
Ali Avatar asked Mar 20 '11 13:03

Ali


1 Answers

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];
like image 147
jscs Avatar answered Oct 24 '22 08:10

jscs