0

嗨,我正在尝试格式化我的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"];

我的问题从这里开始。

4

3 回答 3

2

您已设置日期格式yyyy-MM-dd HH:mm:ss2013-01-09 10:02:45但您的日期字符串是2013-01-09 10:02:45 +0000

从日期字符串中删除区域+0000或在日期格式字符串中包含区域。

于 2013-01-09T10:33:14.120 回答
2

使用这个:

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

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

[df setDateFormat:@"yyyy-MM-dd"];
于 2013-01-09T10:41:52.173 回答
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;

}
于 2013-01-09T10:42:08.700 回答