NSDate to NSString error



我从我的服务器接收了 3 个字符串值,我将它们放入 NSDictionary 中。然后,我将这些值传递给NSDateComponent,然后我尝试创建一个NSDateFormatter,我很确定这是错误的。

日期格式应该是 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应该给你四月而不是04

NSString *str_date = [NSString stringWithFormat:@"%@-%@-%@",[recivedData objectForKey:@"Day"],[recivedData objectForKey:@"Month"],[recivedData objectForKey:@"Year"]];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MM-yyyy"];
NSDate* d = [df dateFromString:str_date];
NSLog(@"%@", d);
[df release];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MMMM-yyyy"];
NSString *stringFromDate = [formatter stringFromDate:d];
NSLog(@"%@",stringFromDate);
[formatter release];
dateResultLabel.text = stringFromDate;
这可能会

对你有所帮助...

 NSDictionary *testDict = [[NSDictionary alloc] init];
[testDict setValue:@"14" forKey:@"Day"];
 [testDict setValue:@"4" forKey:@"Month"];
 [testDict setValue:@"2014" forKey:@"Year"];

NSString *str = [[[NSString stringWithFormat:@"%@-",[testDict objectForKey:@"Day"]] stringByAppendingString:[NSString stringWithFormat:@"%@-",[testDict objectForKey:@"Month"]]] stringByAppendingString:[NSString stringWithFormat:@"%@",[testDict objectForKey:@"Year"]]];


NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:@"dd-MM-yyyy"];

NSDateFormatter *formatter1 = [NSDateFormatter new];
[formatter1 setDateFormat:@"dd-MMM-yyyy"];

NSLog(@"%@",[formatter1 stringFromDate:[formatter dateFromString:str]]);

最新更新