iOS获取当月第一天和最后一天

作者: 阿古斯年 | 来源:发表于2017-06-27 20:05 被阅读1646次
    - (NSArray *)getMonthFirstAndLastDayWith:(NSString *)dateStr{
        
        NSDateFormatter *format=[[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyy-MM-dd"];
        NSDate *newDate=[format dateFromString:dateStr];
        double interval = 0;
        NSDate *firstDate = nil;
        NSDate *lastDate = nil;
        NSCalendar *calendar = [NSCalendar currentCalendar];
    
        BOOL OK = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:& firstDate interval:&interval forDate:newDate];
        
        if (OK) {
            lastDate = [firstDate dateByAddingTimeInterval:interval - 1];
        }else {
            return @[@"",@""];
        }
    
        NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
        [myDateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *firstString = [myDateFormatter stringFromDate: firstDate];
        NSString *lastString = [myDateFormatter stringFromDate: lastDate];
        return @[firstString, lastString];
    }
    

    相关文章

      网友评论

      本文标题:iOS获取当月第一天和最后一天

      本文链接:https://www.haomeiwen.com/subject/opaecxtx.html