日期值为零

时间:2016-08-12 15:03:26

标签: ios objective-c nsdate nsdateformatter

使用字典将一个值添加到NSMutableArray中 SelectedDate =“2016-08-12”;

我正在尝试从MutableArray中获取日期,

   NSDate *dateFromTable = [[Array valueForKey:@"SelectedDate"] objectAtIndex:0];
            NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
            [dateformate setDateFormat:@"dd"];
       NSString   *dateValue = [dateformate stringFromDate:dateFromTable];

dateValue总是返回nil, 不知道我做错了什么。

2 个答案:

答案 0 :(得分:0)

根据您的代码进行调整:

NSArray *array = @[@"2016-08-12"]; // array with dates in string format
NSString *dateFromTable = array.firstObject; // get first element
NSDateFormatter *dateformater =[NSDateFormatter new];
[dateformater setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateformater dateFromString:dateFromTable]; // get date from string
NSLog(@"%@", date); // 2016-08-12 22:00:00 +0000
[dateformater setDateFormat:@"dd"];
NSString *dateValue = [dateformater stringFromDate:date]; // get string from date
NSLog(@"%@", dateValue); // 12

答案 1 :(得分:0)

从数组获取日期到字符串并转换为日期

var

然后,如果您想将日期转换为字符串,请按照以下步骤进行操作

NSString *dateFromTable = [NSString stringWithFormat:@"%@",[[Array valueForKey:@"SelectedDate"] objectAtIndex:0]];
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:@"yyyy-MM-dd"];
NSDate   *dateValue = [dateformate dateFromString:dateFromTable];