ios - NSDate 到 NSString 错误

标签 ios objective-c nsstring uilabel nsdateformatter

我正在从我放入 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/

相关文章:

iOS - 检测静默模式

ios - 容器 View viewcontroller中的UIViewController调用函数

ios - TableView :cellForRowAtIndexPath: returning null

objective-c - 使用偏移量获取 NSString 中字符的索引并在 Objective-C 中使用子字符串

cocoa - Swift 1.2 不愿意我的 NSString "+"map.reduce

objective-c - 如何将 NSString 转换为有效的 NSDate (iOS)

ios - Xamarin——查看生成的 Objective C 代码?

iphone - iOS 应用程序中的维基百科

objective-c - Xcode 在 NSAttributedString 上调用 RTFFromRange 时生成警告,documentAttributes 为 nil

iOS 内存泄漏, View Controller 的自定义 TabBar 失控分配