NSDateFormatter stringFromDate,dateFromString都返回nil

时间:2013-01-09 10:28:57

标签: iphone ios nsstring nsdate nsdateformatter

您好我正在尝试格式化NSString。但它不起作用。我尝试了 stackoverflow 中的所有答案,但没有任何对我有用。

NSLog(@"log 1: %@ %@", [dealDetailsDict objectForKey:@"DealDateViewed"], [[dealDetailsDict objectForKey:@"DealDateViewed"] class]);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"log 2: %@ %@", [df stringFromDate:[dealDetailsDict objectForKey:@"DealDateViewed"]], [df dateFromString:[dealDetailsDict objectForKey:@"DealDateViewed"]]);

我不知道这里有什么问题,stringFromDatedateFromString都返回nil。这是我的NSLog

log 1: 2013-01-09 10:02:45 +0000 __NSCFString
log 2: (null) (null)

我想显示31-12-2010之类的日期。所以我说,

[df setDateFormat:@"dd-MM-yyyy"];

我的问题开始了。

3 个答案:

答案 0 :(得分:2)

您已为[{1}}设置了日期格式yyyy-MM-dd HH:mm:ss,但您的日期字符串为2013-01-09 10:02:45

从日期字符串中删除区域2013-01-09 10:02:45 +0000或在日期格式字符串中包含区域。

答案 1 :(得分:2)

使用这个:

[df setDateFormat:@"yyyy-MM-dd HH:mm:ss z"]; 

然后再次将您需要的格式设置为:

[df setDateFormat:@"yyyy-MM-dd"];

答案 2 :(得分:2)

将以下功能用于日期格式......

-(NSString*) Dateformate:(NSString*)str
{    
    NSDateFormatter *dfrt =[[NSDateFormatter alloc] init];
    [dfrt setDateFormat:@"yyyy-MM-dd h:mm:ss"];
    NSDate *presentdate = [dfrt dateFromString:str];
    [dfrt setDateFormat:@"MMMM"];
    NSString *fullMonth = [dfrt stringFromDate:presentdate];

    [dfrt setDateFormat:@"yyyy"];
    NSString *yearStr = [dfrt stringFromDate:presentdate];
   // NSLog(@"month %@",presentdate);

    [dfrt setFormatterBehavior:NSDateFormatterBehavior10_4];
    [dfrt setDateFormat:@"d"];
    int date_day = [[dfrt stringFromDate:presentdate] intValue];
    NSString *suffix_string = @"|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st";
    NSArray *suffixes = [suffix_string componentsSeparatedByString: @"|"];
    NSString *suffix = [suffixes objectAtIndex:date_day];

    NSString *fullDateFormat = [NSString stringWithFormat:@"%@ %d%@ %@",fullMonth,date_day,suffix,yearStr];

   // NSLog(@"fullDateFormat %@",fullDateFormat);

    return fullDateFormat;

}