2014-01-09 12 views
0

我想設置一個NSDate對象,它可以告訴我一個指定日期是否在兩個其他日期之間,但無視年份。我在我的應用程序中有一些東西在聖誕節做了一些特別的事情,並且我希望在未來的幾年中能夠面向未來。我使用下面的代碼來檢查當前日期是在12月1日到12月31日之間,但我必須指定年份(2013年)。匹配NSDate中任何一年中的給定日期和月份?

我不太確定如何去修改它在任何一年的工作 - 因爲日期被轉換成普通的數字值,它甚至可以完成?

+ (NSDate *)dateForDay:(NSInteger)day month:(NSInteger)month year:(NSInteger)year 
{ 
    NSDateComponents *comps = [NSDateComponents new]; 
    [comps setDay:day]; 
    [comps setMonth:month]; 
    [comps setYear:year]; 
    return [[NSCalendar currentCalendar] dateFromComponents:comps]; 
} 

- (BOOL)laterThan:(NSDate *)date 
{ 
    if (self == date) { 
     return NO; 
    } else { 
     return [self compare:date] == NSOrderedDescending; 
    } 
} 

- (BOOL)earlierThan:(NSDate *)date 
{ 
    if (self == date) { 
     return NO; 
    } else { 
     return [self compare:date] == NSOrderedAscending; 
    } 
} 
+1

根據定義,NSDate是自任意時間參考(1970年1月或2000年1月,取決於您所問的問題)以來的秒數。它不單獨包含月/日/小時/分鐘/秒。 –

+0

(儘管你總是可以創建NSDate對象,其中年份始終爲1970或2000或任何其他值,並比較這些對象,但創建一個「MMddHHmmss」字符串並將其用於所有你的交易。) –

+0

(但是如果你確實使用NSDates,比如你上面描述的比較NSDates的「類別」使得它更容易,更不容易出錯)。 –

回答

2

聽起來你所需要做的就是確定NSDate是否在12月份。我相信你可以做這樣的:

NSDate * now = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *nowComponents = [gregorian components:NSMonthCalendarUnit fromDate:now]; 
if ([nowComponents month] == 12) { 
    // It's December, do something 
} 

如果你不想被限制在一整個月你可以讓你的當前日期的月份和日期的組件。

+0

這看起來很完美,絕對應該工作。非常感謝! – Luke

0

判斷一個日期是在今年晚些時候比我會使用這樣的一些指定日期:

// yearlessDate is in the form MMddHHmmss 
+BOOL date:(NSDate*)theDate isLaterInYearThan:(NSString*)yearlessDate { 
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init]; 
    fmt.dateFormat = @"MMddHHmmss"; 
    NSString* theDateFormatted = [fmt stringFromDate:theDate]; 
    return [theDateFormatted compareTo:yearlessDate] == NSOrderedDescending; 
} 

通常的告誡:重時區,12/24設備設置等會使DateFormatter成爲靜態對象是最佳選擇。

相關問題