gpt4 book ai didi

ios - NSDate 到 NSString 错误

转载 作者:行者123 更新时间:2023-11-28 20:03:49 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com