如何在ios的fscalender中获得第一个日期和月份的最后日期?

时间:2017-07-31 07:17:45

标签: ios objective-c calendar fscalendar

如何获取月历开始和结束日期?

从截图中,我需要在fscalender中获得2017年8月1日和2017年8月31日?

当我滚动然后这个方法调用但每次都获得当前日期

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar;
{

}

谢谢!

enter image description here

5 个答案:

答案 0 :(得分:0)

您可以根据需要使用这两种NSDate类别方法:

- (NSDate *)startDateOfMonth {
    NSCalendar *current = [NSCalendar currentCalendar];
    NSDate *startOfDay = [current startOfDayForDate:self];
    NSDateComponents *components = [current components:(NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:startOfDay];
    NSDate *startOfMonth = [current dateFromComponents:components];
    return startOfMonth;
}

- (NSDate *)endDateOfMonth {
    NSCalendar *current = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = 1;
    components.day = -1;
    NSDate *endOfMonth = [current dateByAddingComponents:components toDate:[self startDateOfMonth] options:NSCalendarSearchBackwards];
    return endOfMonth;
}

您需要将日期从FSCalendar转换为NSDate

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar {
    NSDate *date = ... //Conversion goes here

    NSDate *startDateOfMonth = [date startDateOfMonth];
    NSDate *endDateOfMonth = [date endDateOfMonth];

    // convert back if you need to
}

答案 1 :(得分:0)

FSCalendar属性currentPage会返回当前显示页面的开始日期 - 这是一个月或一周的第一天,具体取决于您是显示月份还是一周。

然后使用NSCalendar方法查找以currentPage开头的月份或周的最后一天。有很多方法可以做到这一点;例如添加NSDateComponents值或使用其中一种“下一步”方法,例如nextDateAfterDate:matchingUnit:value:options:

HTH

答案 2 :(得分:0)

获取第一个日期

 - (void)calendarCurrentPageDidChange:(FSCalendar *)calendar;
    {
        NSLog(@"did change to page %@",[self.dateFormatter stringFromDate:calendar.currentPage]);

    }

答案 3 :(得分:0)

-(void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    [self.calendar selectDate:[self.calendar.currentPage fs_firstDayOfMonth]];
    [self.calendar selectDate:[self.calendar.currentPage fs_lastDayOfMonth]];
}

答案 4 :(得分:-1)

您自己获得当月的第一个和最后一个日期。无需从FSCalendar获取它。为此,请参见下面的代码。

NDDate *currentDate = //Pass date which you get
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:currentDate];
[comp setMonth:[comp month]];
[comp setDay:1];
NSDate *firstDayDate = [gregorian dateFromComponents:comp];
[comp setMonth:[comp month]+1];
[comp setDay:0];
NSDate *lastDayDate = [gregorian dateFromComponents:comp];

NSLog(@"First : %@, Last : %@",firstDayDate,lastDayDate);

这样您就可以获得第一个和最后一个日期。