2012-07-12 69 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 
    }