我正在从我放入 NSDictionary 的服务器中接收 3 个字符串值。然后我将这些值传递给 NSDateComponent,之后我尝试创建一个 NSDateFormatter,我很确定这是错误的。
Date formate 应该是 01-April-2014 我收到的数据应该是这样的
{
Day @"1"
Month @"4"
Year @"2014"
}
在下面的代码中,您将看到我已尝试这样做,但我在两个方面遇到了麻烦,NSDateFormatter 的格式,其次我如何将日期传递到 NSString 中,以便我可以在我的标签中显示它。
NSDateComponents *recivedDate = [[NSDateComponents alloc] init];
[recivedDate setDay:[[recivedData objectForKey:@"Day"] intValue]];
[recivedDate setMonth:[[recivedData objectForKey:@"Month"] intValue]];
[recivedDate setYear:[[recivedData objectForKey:@"Year"] intValue]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-mm-yyy"];
NSString *dateString = [formatter stringFromDate:recivedDate];
dateResultLabel.text = dateString;
最佳答案
您已经很好地将日期组件分成两部分,但您没有从中创建 NSDate 对象。 使用
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *date = [calendar dateFromComponents:recivedDate];
然后使用您的代码将其更改为字符串
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MMM-yyy"];
NSString *dateString = [formatter stringFromDate:date];
dateResultLabel.text = dateString;
ps:MMM应该给你April而不是04
关于ios - NSDate 到 NSString 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22905511/