Reputation: 930
I know this question has been asked before (most notably here: Converting NSString to NSDate (and back again)), but I am having difficulties. I am using an RSS feed parser which returns a date in this format:
Fri, 23 Nov 2012 15:39:00 -0800
I wish to convert it to this format:
Nov. 23 2012
WIth a separate time formatted like this:
3:39:00 PM
Here is the code I currently have:
NSString *RSSDate1=@"Fri, 23 Nov 2012 15:39:00 -0800";
NSDateFormatter *RSSDateFormatter = [[NSDateFormatter alloc] init];
[RSSDateFormatter setDateFormat:@"D, d M Y H:i:s O"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [RSSDateFormatter dateFromString:RSSDate1];
[RSSDateFormatter release];
NSDateFormatter *RSSDateFormatter2=[[NSDateFormatter alloc] init];
[RSSDateFormatter2 setDateStyle:NSDateFormatterShortStyle];
UIAlertView *dateAlert=[[UIAlertView alloc] init];
[dateAlert setTitle:[RSSDateFormatter2 stringFromDate:dateFromString]];
[dateAlert addButtonWithTitle:@"Dismiss"];
[dateAlert show];
[dateAlert release];
Right now, the string is returning nil, so I'm betting my formatting is off. Any help would be appreciated. Thanks!
Upvotes: 1
Views: 115
Reputation: 23278
Change it to,
NSString *RSSDate1 = @"Fri, 23 Nov 2012 15:39:00 -0800";
NSDateFormatter *RSSDateFormatter = [[NSDateFormatter alloc] init];
[RSSDateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss zzzzz"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [RSSDateFormatter dateFromString:RSSDate1];
NSLog(@"dateFromString = %@", dateFromString);
[RSSDateFormatter release];
NSDateFormatter *RSSDateFormatter2 = [[NSDateFormatter alloc] init];
[RSSDateFormatter2 setDateFormat:@"MMM dd, yyyy hh:mm aaa"];
NSLog(@"dateToString = %@", [RSSDateFormatter2 stringFromDate:dateFromString]);
UIAlertView *dateAlert = [[UIAlertView alloc] init];
[dateAlert setTitle:[RSSDateFormatter2 stringFromDate:dateFromString]];
[dateAlert addButtonWithTitle:@"Dismiss"];
[dateAlert show];
[dateAlert release];
Output:
dateToString = Nov 23, 2012 03:39 PM
Note that the format for "Fri, 23 Nov 2012 15:39:00 -0800" is "EEE, dd MMM yyyy HH:mm:ss zzzzz" and for "Nov 23, 2012 03:39 PM" it is "MMM dd, yyyy hh:mm aaa". Each letters in the format represents the corresponding word in date string. For eg:- EEE is for Fri, aaa for PM etc.. Check this for more information on how to do this formatting.
Upvotes: 0
Reputation: 16392
You might try using this configured NSDateFormatter to convert the current date (now) to an NSString and print out the string. Look at the format that's output and compare it to the format you want. The difference(s) should clue you in as to what you need to change to get your desired format.
Upvotes: 1