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

后端 未结 2 1133
我寻月下人不归
我寻月下人不归 2020-12-01 12:15

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 tim

相关标签:
2条回答
  • 2020-12-01 12:49

    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];
    }
    
    0 讨论(0)
  • 2020-12-01 13:06
    -(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 讨论(0)
提交回复
热议问题