美文网首页
IOS 获取当月第一天和最后一天

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

作者: 丶小杨_ | 来源:发表于2019-02-14 16:36 被阅读25次
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *currentTime2 = [formatter stringFromDate:[NSDate date]];
    
    NSArray * arr =[self getMonthFirstAndLastDayWith:currentTime2];
    
    //方法
    - (NSArray *)getMonthFirstAndLastDayWith:(NSString *)dateStr{
        
        NSDateFormatter *format=[[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyy-MM"];
        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/heoeeqtx.html