Reputation: 123
I am trying to get a string from NSDate object type and display it in a label. Here is the code I am using,
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
//[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *datey = [dateFormatter dateFromString:selectedDate];
NSString *labelData = [dateFormatter stringFromDate:datey];
dateLabel.Text = labelData;
where selectedDate is a String containing date in yyyy-mm-dd format. The label is not showing up the date. But if I try giving it a string like @"someblah", it is displaying. Where am I going wrong?? Help appreciated. Thanks
Upvotes: 2
Views: 5595
Reputation: 70155
Your line dateLabel.Text
should be dateLabel.text
.
So you start with a date string, convert it to a date, and then convert it back to a string using the same formatter. Isn't it easier to use:
dateLabel.text = selectedDate;
In all likelihood you are trying to create an NSDate using a date string that is inconsistent with the format. For example, if the format is @"yyyy-MM-dd"
but your selectedDate differs from that format then the formatter won't return a NSDate. You can avoid this by setting the DateFormat to be correct for the selectedDate and then, once parsed, change the DateFormat for the desired output. Or use two NSDateFormatter
instances.
Upvotes: 2
Reputation: 1148
Try specifying a specific format instead of NSDateFormatLongStyle
, for example
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
I found this answer in 2 seconds using google.. (Yes thats a hint)
Upvotes: 1