Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing time components from an NSDate object using Objective C/Cocoa

Tags:

I'm trying to write a simple function using Objective C that accepts an NSDate object and returns an NSDate object that contains the same date value but has removed any time components from the date.

For example if I were to pass an NSDate with a value of '2010-10-12 09:29:34' the function would return 2010-10-12 00:00:00.

The I'm using function seems to work properly. However, when I test the iPhone app I'm developing with Instruments it reports there is a memory leak in the function I'm using. Take a look at my function below. Where is there a memory leak? Is there a better way to achieve the functionality I desire?

Thanks in advance!!

-(NSDate *)dateWithOutTime:(NSDate *)datDate
{
    if (datDate == nil)
    {
        datDate = [NSDate date];
    }

    unsigned int      intFlags   = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar       *calendar   = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];

     components = [calendar components:intFlags fromDate:datDate];

     return [calendar dateFromComponents:components];
}
like image 749
CMJ Designs Avatar asked Oct 12 '10 15:10

CMJ Designs


2 Answers

Try this:

-(NSDate *)dateWithOutTime:(NSDate *)datDate {
    if( datDate == nil ) {
        datDate = [NSDate date];
    }
    NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:datDate];
    return [[NSCalendar currentCalendar] dateFromComponents:comps];
}
like image 76
aegzorz Avatar answered Jan 25 '23 22:01

aegzorz


-(NSDate *)dateWithOutTime:(NSDate *)datDate{
    if( datDate == nil ) {
        datDate = [NSDate date];
    }
    NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:datDate];
    [comps setHour:00];
    [comps setMinute:00];
    [comps setSecond:00];
    [comps setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    return [[NSCalendar currentCalendar] dateFromComponents:comps];
}
like image 36
Shehbaz Khan Avatar answered Jan 25 '23 22:01

Shehbaz Khan