美文网首页iOS开发点滴
IOS 获取某月的第一天和最后一天

IOS 获取某月的第一天和最后一天

作者: 本客 | 来源:发表于2021-11-03 11:31 被阅读0次

    //获取某月的第一天字符串

    -(NSString *)getMonthFirstDayWithDate:(NSDate *)date format:(NSString *)aformat{

        NSDate * newDate = date;

        double interval = 0;

        NSDate * firstDate = nil;

        NSCalendar * calendar = [NSCalendar currentCalendar];

        BOOL bl = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDate interval:&interval forDate:newDate];

        if(bl) {

            NSDateFormatter * myDateFormatter = [[NSDateFormatter alloc]init];

            [myDateFormatter setDateFormat:aformat];

            NSString * firstString = [myDateFormatter stringFromDate: firstDate];

            return firstString;

        }

        return @"";

    }

    //获取某月的最后一天字符串

    -(NSString *)getMonthLastDayWithDate:(NSDate *)date format:(NSString *)aformat{

        NSDate * newDate = date;

        double interval = 0;

        NSDate * firstDate = nil;

        NSDate * lastDate = nil;

        NSCalendar * calendar = [NSCalendar currentCalendar];

        BOOL bl = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDate interval:&interval forDate:newDate];

        if(bl) {

            lastDate = [firstDate dateByAddingTimeInterval:interval -1];

            NSDateFormatter * myDateFormatter = [[NSDateFormatter alloc]init];

            [myDateFormatter setDateFormat:aformat];

            NSString * lastString = [myDateFormatter stringFromDate:lastDate];

            return lastString;

        }

        return @"";

    }

    //调用某月第一天方法

    [self getMonthFirstDayWithDate:[NSDate date] format:@"yyyy-MM-dd"];

    //调用某月最后一天方法

    [self getMonthLastDayWithDate:[NSDate date] format:@"yyyy-MM-dd"];

    相关文章

      网友评论

        本文标题:IOS 获取某月的第一天和最后一天

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