2012-07-12 82 views
-6

可能重複:
How can I calculate the difference between two dates?
NSDate, comparing two dates如何檢查2天是否有差異30天?

我有兩個日期。如何檢查他們之間是否有30天的差異? 我實際上有一個應用程序內購買,每購買30天后需要禁用。 當用戶購買功能時,日期被保存,所以我需要檢查日期。如果30天過去了,我需要再次禁用該功能。

+4

請學會用對堆棧的搜索功能溢出。這個問題之前已經被問了很多次了。 – 2012-07-12 11:48:36

+0

可能重複的[如何計算兩個日期之間的差異?](http://stackoverflow.com/questions/4371757/how-can-i-calculate-the-difference-between-two-dates),[Number兩天之間的天數](http://stackoverflow.com/questions/4739483/number-of-days-between-two-nsdates) – 2012-07-12 16:49:06

回答

6

你既可以日期轉換爲與timeIntervalSince1970然後秒檢查差值是否大於2592000(30 * 24 * 60 * 60,即30天* 24小時* 60分鐘* 60秒)。

NSTimeInterval difference = [date1 timeIntervalSince1970] - [date2 timeIntervalSince1970]; 

if(difference >2592000) 
{ 
//do your stuff here 
} 

編輯: 更緊湊的版本,你可以使用- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

NSTimeInterval difference = [date1 timeIntervalSinceDate:date2]; 
if(difference >2592000) 
{ 
    //do your stuff here 
} 
+0

這將失敗的DST時間。 – vikingosegundo 2016-07-13 18:15:04

+0

@vikingosegundo真的嗎?爲什麼會失敗? – Michal 2016-07-14 13:48:54

+0

因爲不是每天都有24小時。在一天中有DST的地區有23個,25個。 – vikingosegundo 2016-07-14 14:01:24

-1

您可以創建一個日期是+從現在天?

NSDate *thrityDaysPlus = [[NSDate date] dateByAddingTimeInterval:3600*24*30] 

,然後簡單地把它比作你的保存日期

if ([date1 compare:date2] == NSOrderedDescending) { 
    NSLog(@"date1 is later than date2");   

} else if ([date1 compare:date2] == NSOrderedAscending) { 
    NSLog(@"date1 is earlier than date2"); 

} else { 
    NSLog(@"dates are the same"); 

} 
+0

將失敗,當涉及到DST – vikingosegundo 2016-07-13 18:15:38

1

提供開始和下面的方式結束的NSDate:

NSDate *date_Start; 
    NSDate *date_End; 
    NSCalendar *cal=[NSCalendar currentCalendar]; 
NSDateComponents *components=[cal components:NSDayCalendarUnit fromDate:date_Start toDate:date_End options:0]; 
    int days=[components day]; 
    if(days>30){ 
    //Your code here 
    }