如何使用formatter将字符串日期转换为nsdate?

时间:2016-06-13 11:35:32

标签: ios objective-c nsdate nsformatter

我关注stackOverflow回答并编写代码,但我不知道发生了什么。它不会起作用。 PLZ,任何人都可以为我解决。我用愚蠢的代码......

        NSMutableArray *movieDate;
    NSArray *temp1 = [_dicUpcomingMovie objectForKey:@"results"];
    for (NSDictionary *temp2 in temp1)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

        NSString *datestring = [temp2 valueForKey:@"release_date"];
        //NSDate *myDate = [[NSDate alloc]init];
        [formatter setDateFormat:@"dd MMM,YYYY"];
        NSDate *date = [formatter dateFromString:datestring];
        NSLog(@"%@",date);
        [movieDate addObject:date];
        NSLog(@"%@",movieDate);
    }

所以就是这样。上面的代码不起作用myDate对象仍然没有

3 个答案:

答案 0 :(得分:0)

我认为datestring与您指定的格式不符。有关完整示例,请参阅NSDateFormatter

答案 1 :(得分:0)

    NSMutableArray *movieDate=[[NSMutableArray alloc]init];;
   NSArray *temp1 = [_dicUpcomingMovie objectForKey:@"results"];
  NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    for (int i=0 ;i<temp1.count;i++)
  {


    NSString *datestring = [[temp1   objectatindex:i]valueForKey:@"release_date"];

  [serverFormatter setTimeZone:[NSTimeZone localTimeZone]];
  [serverFormatter setDateFormat:@"dd,MMM,YYYY"];
   NSDate *date = [serverFormatter dateFromString:dateString1];

    [movieDate addObject:date];

}
   NSLog(@"%@",movieDate);

答案 2 :(得分:-1)

试试这个,

NSMutableArray *movieDate;
    NSArray *temp1 = [_dicUpcomingMovie objectForKey:@"results"];
    for (NSDictionary *temp2 in temp1)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

        NSString *datestring = [temp2 valueForKey:@"release_date"];
        //NSDate *myDate = [[NSDate alloc]init];
        [formatter setDateFormat:@"dd MM,YYYY"];
        NSDate *date = [formatter dateFromString:datestring];
        NSLog(@"%@",date);
        [movieDate addObject:date];
        NSLog(@"%@",movieDate);
    }