hanumanDev
hanumanDev

Reputation: 6614

How to convert an NString to an NSDate and then set the date to a UILabel

I need to convert the following string into a better readable format:

NSString *deadlineFromTable = @"2012-11-13T22:59:00.000Z";

I would like to convert this into an NSDate, so I can format it.

I tried the following, but I get an incompatible pointer error assigning NSString to NSDate when I try to set it to a UILabel (the last line):

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];

NSDate *dateFromString = [dateFormatter dateFromString:deadlineFromTable];
self.deadlineLbl.text = dateFromString;

Thanks for any help.

Upvotes: 0

Views: 1432

Answers (2)

calimarkus
calimarkus

Reputation: 9977

You need to use the dateFormatter twice. Once for parsing, and once for formatting your string.
You cannot assign a date as a label text directly.

  1. Set format: yyyy-MM-dd'T'HH:mm:ss.Z and then use
    NSDate *date = [dateFormatter dateFromString:dedlineFromTable];
  2. Set format: dd-MM-yyyy and then use
    NSString *text = [dateFormatter stringFromDate: date];

Upvotes: 3

Fogmeister
Fogmeister

Reputation: 77631

You need two dateFormatters.

One to convert from your input string to a date and then one to convert from that date into the Label format you want.

You also need to change the format of the date formatter so it matches your string...

NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init];
[dateStringParser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.Z"];

NSDate *date = [dateStringParser dateFromString:deadlineFromTable];

NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init];
[labelFormatter setDateFormat:@"dd-MM-yyyy"];

self.deadlineLbl.text = [labelFormatter stringFromDate:date];

That should do it.

Upvotes: 1

Related Questions