How do I create the current date (or any date) as an NSDate without hours, minutes and seconds?

后端 未结 2 1324
刺人心
刺人心 2020-12-06 07:57

I need to create an NSDate of the current date (or on any NSDate) without the hours, minutes and seconds and keep it as an NSDate, in as few lines

相关标签:
2条回答
  • 2020-12-06 08:25

    First, you have to understand that even if you strip hours, minutes and seconds from an NSDate, it will still represent a single moment in time. You will never get an NSDate to represent an entire day like 2011-01-28; it will always be 2011-01-28 00:00:00 +00:00. That implies that you have to take time zones into account, as well.

    Here is a method (to be implemented as an NSDate category) that returns an NSDate at midnight UTC on the same day as self:

    - (NSDate *)midnightUTC {
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        [calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    
        NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                                       fromDate:self];
        [dateComponents setHour:0];
        [dateComponents setMinute:0];
        [dateComponents setSecond:0];
    
        NSDate *midnightUTC = [calendar dateFromComponents:dateComponents];
        [calendar release];
    
        return midnightUTC;
    }
    
    0 讨论(0)
  • 2020-12-06 08:30
    NSDate *oldDate = [NSDate date];
    NSCalendarUnit requiredDateComponents = NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit;    
    NSDateComponents *components = [[NSCalendar currentCalendar] components:requiredDateComponents fromDate:oldDate]; 
    NSDate *newDate = [[NSCalendar currentCalendar] dateFromComponents:components];
    
    0 讨论(0)
提交回复
热议问题