Objective c NSDateComponents:查找早于30天的
使用Objective c NSDateComponents:查找早于30天的,objective-c,nsdatecomponents,date-comparison,Objective C,Nsdatecomponents,Date Comparison,使用NSDateComponents我想将出发日期与现在进行比较,看看出发日期是否大于30天 我使用了NSDateComponents功能,但在调试它时,它总是像一个非常大的数字,当我期望它是3天,或15天或任何时候 NSDate* now = [NSDate date]; NSUInteger unitFlags = NSDayCalendarUnit; NSCalendar *calendar = [[NSCalendar alloc] initWithCalenda
NSDateComponents
我想将出发日期与现在进行比较,看看出发日期是否大于30天
我使用了NSDateComponents
功能,但在调试它时,它总是像一个非常大的数字,当我期望它是3天,或15天或任何时候
NSDate* now = [NSDate date];
NSUInteger unitFlags = NSDayCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:unitFlags fromDate:departureDate toDate:now options:0];
NSInteger age = [components day]+1;
当我尝试记录年龄时
NSLog(@“年龄(天)=%lu),(长)年龄)代码>
它返回一个非常长的数字,如18446744073709551613
我想做一个if声明,声明:
如果(年龄>30)
但我不确定当返回的年龄是这样一个长的数字时如何执行此操作
非常感谢
NSDate * dateNotFormatted = [NSDate date];
double now = [dateNotFormatted timeIntervalSince1970];
NSLog(@"%f",now);
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate * dateDepareture =[dateFormatter dateFromString:@"29-06-2015"];
double dateDept = [dateDepareture timeIntervalSince1970];
NSLog(@"%f",dateDept);
在30天内检查doublevalue
或
NSDateComponents *components;
NSInteger days;
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:[NSDate date] toDate:[dateFormatter dateFromString:@"2-07-2015"] options:0];
days = [components day];
NSLog(@"%ld",(long)days);
将代码更改为需要检查30天
NSDayCalendarUnit NS_CALENDAR_ENUM_已弃用(10_4、10_10、2_0、8_0、,
“改用NSCalendarUnitDay”)=NSCalendarUnitDay
NSDate*date30=[NSDate-date];
date30=[date-dateByAddingInterval:86400*30];
如果([departureDate compare:date30]==取消搜索){
//出发时间>今天+30天
}
其他的
{
//起飞时间<今天+30天
}
这是您需要的吗?您是否记录了departureDate
和now
?我认为[components day]
也应该是负数,因为我猜出发日期
比现在
晚。因此,您的测试>30
不应正确触发。NSLog(@“age”)
logsage
,而不是名为age
的变量的内容。请向我们展示真实的日志代码。您是正确的,NSLog age不会记录年龄。我更新了发布,需要添加days=([components day]+1)代码>我对正好30天前的时间戳进行了测试,结果是29天而不是30天
NSDate* date30 = [NSDate date];
date30 = [date dateByAddingInterval:86400*30];
if([departureDate compare:date30] == NSOrderedDescending){
//Departure > Today + 30d
}
else
{
//Departure < Today + 30d
}