开发者

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

开发者 https://www.devze.com 2023-01-19 13:05 出处:网络
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 d开发

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 d开发者_C百科ate.

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];
}


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];
}


-(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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消