Navi
Navi

Reputation: 1686

How to retrieve NSDate from date time format?

I want to check two dates: one is in my plist in the following NSString format 2013-08-03 12:26:33 +0000

But, I only need 2013-08-03, how can I remove rest of the time values? Please help me.

I am checking dates using following code, it's working for me. But I only need to retrieve the date part in 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]);

Upvotes: 1

Views: 1304

Answers (1)

Lucas Eduardo
Lucas Eduardo

Reputation: 11655

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.

Upvotes: 2

Related Questions