Realinstomp
Realinstomp

Reputation: 532

String to NSDate problems

I can't get NSDate working for the life of me, even thought I've scanned the questions on Stack Overflow, so help would be greatly appreciated.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 NSString *publishedText = [NSString stringWithFormat:@"%@", feedLocal.published];
cell.publishedLabel.text = publishedText;
    return cell;
}

gives me the string:

2013-05-08 18:09:37 +0000

which I'm trying to turn into: May 8, 2013 6:45PM

I've tried using:

    NSString *publishedText = [NSString stringWithFormat:@"%@", feedLocal.published];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [df dateFromString:publishedText];
    cell.publishedLabel.text = dateFromString;

But it doesn't work and shows a warning that pointer types are incompatible (NSString to NSDate_strong). Thanks for the help!

Upvotes: 0

Views: 109

Answers (2)

danypata
danypata

Reputation: 10175

You are assigning aNSDate to a NSString cell.publishedLabel.text = dateFromString; (I suppose that the cell.publishedLabel.text is a NSString.

EDIT

I didn't test this code but I think the output should be ok if not please check iOS date formatting guide

So after you are parsing the string and you create the NSDate instance add the following code:

EDIT 2 -- FULL CODE

NSString *publishedText = [NSString stringWithFormat:@"%@", feedLocal.published];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
NSDate *dateFromString = [df dateFromString:publishedText];

NSDateFormatter *secondDateFormatter= [[NSDateFormatter alloc] init];
[secondDateFormatter setDateStyle:NSDateFormatterLongStyle];
cell.publishedLabel.text = [secondDateFormatter stringFromDate:dateFromString];

Upvotes: 3

rmaddy
rmaddy

Reputation: 318774

From what you have posted, it would appear that feedLocal.published is an NSDate.

Since your goal is to convert this date to a string, you need something like this:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMMM d, yyyy h:mma"]; // this matches your desired format
NSString *dateString = [df stringFromDate:feedLocal.published];
cell.publishedLabel.text = dateString;

Since your app can be used by people all over the world, I suggest you setup your date formatter like this:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterLongStyle];
[df setTimeStyle:NSDateFormatterShortStyle];

Do this instead of setting a specific date format. Then the date and time will appear appropriate to all users of your app and not just those in a specific country.

Upvotes: 2

Related Questions