I’m trying to use NSDateFormatter with the following code. This is the code within my DetailViewController.m. I’m using Xcode 4.2 with Storyboards and Core Data. I’ve searched other topics here for NSDateFormatter and it seems as though I’m doing this correctly but the results return null.
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
// Format Date to MMM D, YYYY H:MM:SS AM/PM
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *sessDate = [[self.detailItem sessionDate] description];
NSDate *date = [dateFormatter dateFromString:sessDate];
NSString *formattedDate = [dateFormatter stringFromDate:date];
self.sessionDate.text = formattedDate;
NSLog(@"sessDate = %@",sessDate);
NSLog(@"date = %@",date);
NSLog(@"formattedDate = %@",formattedDate);
}
}
NSLog results:
2012-02-10 17:18:17.781 ClickIt[332:10103] sessDate = 2012-02-09 17:11:33 +0000
2012-02-10 17:18:17.782 ClickIt[332:10103] date = (null)
2012-02-10 17:18:17.782 ClickIt[332:10103] formattedDate = (null)
I’ve used NSDateFormatter before and it worked fine but I’m stumped as to why the date variable is returning null. Any thoughts as to what I’m doing wrong?
Thanks!
adjusted code
// Format Date to MMM D, YYYY H:MM:SS AM/PM
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSString *sessDate = [[self.detailItem sessionDate] description];
NSDate *date = [dateFormatter dateFromString:sessDate];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *formattedDate = [dateFormatter stringFromDate:date];
self.sessionDate.text = formattedDate;
I think NSDateFormatterMediumStyle corresponds to something like this – Nov 23, 1937. Hence you are getting null value.
Can you try this?