Stas
Stas

Reputation: 9935

Convert NSString date to NSDate or a specific string

Could you please help me with such converting I have NSString date like @"2/8/2012 7:21:09 PM" And I need to have such string in output: "at 7:21 PM, february 8" I've tried to use dateFormatter with different date patterns but it always return me null..I really don't understandd where I'm doing wrong :(

NSString *dateString = newsItem.Date;//Which is equal to @"2/8/2012 7:21:09 PM"
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm/dd/yyyy hh:mm:ss"];//I'm sure that this patternt is wrong but have no idea how to write the right one
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
NSLog(@"date:%@", dateFromString);

Upvotes: 2

Views: 848

Answers (1)

DHamrick
DHamrick

Reputation: 8488

You'll need to use two different date formatters. First one to convert the string in to a date, the second one to output the date as a string with the specified format.

NSString* dateString = @"2/8/2012 7:21:09 PM";
NSDateFormatter* firstDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[firstDateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate* date = [firstDateFormatter dateFromString:dateString];

NSLog(@"Date = %@",date);

NSDateFormatter* secondDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[secondDateFormatter setDateFormat:@"h:mm a, MMMM d"];
NSString* secondDateString = [NSString stringWithFormat:@"at %@",[secondDateFormatter stringFromDate:date]];

NSLog(@"%@",secondDateString);

The trick is the date format strings. They use a format called the unicode date format, the specification can be found here.

Upvotes: 2

Related Questions