2014-08-28 47 views
1
開始

我有以下的方法,它可以幫助我判斷當前日期是從本月的最後3天或更少:試圖確定該月的當前日期是本月的iOS中

- (BOOL) checkMonthEnd { 

    NSDate *now = [NSDate date]; 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSDate *startOfToday; 
    [cal rangeOfUnit:NSCalendarUnitDay startDate:&startOfToday interval:NULL forDate:now]; 

    NSDate *startOfNextMonth = ({ 
     NSDate *startOfThisMonth; 
     NSTimeInterval lengthOfThisMonth; 
     [cal rangeOfUnit:NSCalendarUnitMonth startDate:&startOfThisMonth interval:&lengthOfThisMonth forDate:now]; 
     [startOfThisMonth dateByAddingTimeInterval:lengthOfThisMonth]; 
    }); 

    NSDateComponents *comp = [cal components:NSCalendarUnitDay fromDate:startOfToday toDate:startOfNextMonth options:0]; 
    if (comp.day < 4) { 
     return YES; 
    } else { 
     return NO; 
    } 
} 

我想要做的是現在修改它,以便它顯示當前日期是否在本月開始的前三天內。有人可以告訴我如何做到這一點?

在此先感謝所有回覆的人。

+0

該日曆月還是該月的前三個工作日?首先 - 看看日期的日期組件 - 如果它<4,那麼它是在前三天內 – Paulw11 2014-08-28 23:02:32

回答

4

以確定它是否是這個月的前三天中的一個,只是檢索NSCalendarUnitDay,看看它是否小於4:

- (BOOL) checkMonthStart { 
    NSDate *now = [NSDate date]; 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSDateComponents *components = [cal components:NSCalendarUnitDay fromDate:now]; 
    return components.day < 4; 
} 

順便說一句,如果檢查你是否是內本月底三天,我可能會建議:

- (BOOL) checkMonthEnd { 
    NSDate *now = [NSDate date]; 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSDateComponents *components = [cal components:NSCalendarUnitDay fromDate:now]; 

    NSRange range = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:now]; 

    return (range.length - components.day) < 3; 
} 
相關問題