如何解析日期字符串

时间:2011-05-24 13:33:14

标签: iphone objective-c

我使用此代码以这种格式“01-05-2011”

从字符串中获取信息
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"dd'-'MM'-'yyyy"];
    // Your date represented as a NSDate
    NSDate *dateDepart = [formatter dateFromString:daparatureFly.date];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                                              fromDate:dateDepart];

然后当我拿这个月[comps day],[comps month],我有1和5,我想要01,05。任何人都可以帮助我吗?感谢名单

2 个答案:

答案 0 :(得分:2)

这些组件是NSSintegers,它们没有格式化。在字符串中使用它时,您可以执行以下操作:

NSString *day = [NSString stringWithFormat:@"%02d", [comps day]];

答案 1 :(得分:0)

类似于......

//UNTESTED
[NSString stringWithFormat:@"%02d", [comps day]];