2

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

4

2 回答 2

2

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.

于 2013-07-12T21:54:07.807 回答
1

尝试指定特定格式而不是NSDateFormatLongStyle,例如

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

我使用谷歌在 2 秒内找到了这个答案。(是的,这是一个提示)

于 2013-07-12T21:13:56.317 回答