Wednesday, May 16, 2012

Forming NSString "2012-06-29" into NSDate's "NSDateFormatterMediumStyle"?

I'm trying to separate the month and day from the following string.



2012-06-29


I've tried formatting the string into the medium style by doing the following:



//Setting Up My Formatter
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];

Forming String Into Formatted Date
NSDate *dateFromString = [formatter dateFromString:event.date];

//Separating Components
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:dateFromString];

//Assigning Each Component to my Cell's Labels
cell.dayLabel.text = [NSString stringWithFormat:@"%d", [components day]];
cell.monthLabel.text = [NSString stringWithFormat:@"%d", [components month]];


When I ran the NSLogs my "event.date" came back "2012-06-26 & dateFromString came back null. Can anyone help guide my in the right direction? Thanks a lot!



EDIT:



So I finally figured out from your help that I was setting the format incorrectly. Instead of using:



[formatter setDateStyle:NSDateFormatterMediumStyle];


I am now using:



[formatter setDateFormat:@"yyyy-MM-dd"];


Here is my question though, from the components, the month is coming back as an integer (1, 2, 3) but I want it to come back as "MMM" (Jan, Feb, Mar). Thanks!





No comments:

Post a Comment