1

我想检查两个日期:一个在我的 plist 中,NSString格式 如下2013-08-03 12:26:33 +0000

但是,我只需要 2013-08-03,如何删除其余的时间值?请帮我。

我正在使用以下代码检查日期,它对我有用。但我只需要检索日期部分 2013-08-03 12:26:33 +0000

 NSString *start = @"2013-08-03 ";
    NSString *end = @"2013-08-05";

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [f dateFromString:start];
    NSDate *endDate = [f dateFromString:end];


    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                        fromDate:startDate
                                                          toDate:endDate
                                                         options:0];

    NSLog(@"%ld", [components day]);
4

1 回答 1

2

So, if all you want it's just a string with the date part, simply use a dateFormatter, similar what you've done before.

Assuming that you have a reference to some date that you want a string part of it, I encapsulated a method that returns a string with the date part:

-(NSString*) stringDatePartOf:(NSDate*)date
{
    NSDateFormatter *formatter = [[NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    return [formatter stringFromDate:date];
}

For example, if you pass a date with the value 2013-08-03 12:26:33 +0000, this method will return 2013-08-03 , like you wanted.

于 2013-08-04T06:15:04.227 回答