Truncate NSDate (Zero-out time)

前端 未结 6 885
孤街浪徒
孤街浪徒 2020-12-02 19:02

I want to generate a new NSDate with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any r

6条回答
  •  时光取名叫无心
    2020-12-02 19:15

    Use NSCalendar's rangeOfUnit:startDate:interval:forDate:. This code will choose the day boundary based on the current time zone. If you want a particular time zone, you need to create an NSCalendar and set its time zone appropriately.

    - (NSDate*)boundaryForCalendarUnit:(NSCalendarUnit)calendarUnit
    {
        NSDate *boundary;
        [[NSCalendar currentCalendar] rangeOfUnit:calendarUnit startDate:&boundary interval:NULL forDate:self];
        return boundary;
    }
    
    - (NSDate*)dayBoundary
    {
        return [self boundaryForCalendarUnit:NSDayCalendarUnit];
    }
    

提交回复
热议问题