NSDate beginning of day and end of day

后端 未结 23 2091
广开言路
广开言路 2020-11-29 23:28
    -(NSDate *)beginningOfDay:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSMonthCalend         


        
23条回答
  •  清歌不尽
    2020-11-30 00:17

    For me none of the answers here and else where on stackoverflow worked. To get start of today i did this.

    NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
    [gregorian setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];    
    NSDateComponents *components = [gregorian components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]]; 
    [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
    NSDate *beginningOfToday = [gregorian dateFromComponents:components];
    

    Note this [gregorian setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; and [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];.

    When a calendar is created it gets initialised with current timezone and when date is extracted from its components, since NSDate has no timezone, the date from current timezone is considered as UTC timezone. So we need to set the timezone before extracting components and later when extracting date from these components.

提交回复
热议问题