我需要检查一个事件日期,该日期应该是当前日期和现在的60天之间。使用下面的代码,但它无法正常工作。请注意,我得到这样的事件字符串 - " 2012-04-14T16:50:02Z"来自我的服务器。
// current date
double currDateInMilliSecs = [NSDate timeIntervalSinceReferenceDate] * 1000;
NSLog(@"currDateInMilliSecs: %f", currDateInMilliSecs);
// sixty days
double sixtydaysvalue = 60.0 * 24.0 * 3600.0 * 1000.0;
NSLog(@"sixtydaysvalue: %f", sixtydaysvalue);
// add current date + sixt days
double sixtyDaysMilliSecsFromCurrDate = currDateInMilliSecs + sixtydaysvalue;
NSLog(@"sixtyDaysMilliSecsFromCurrDate: %f", sixtyDaysMilliSecsFromCurrDate);
// check does the event date between current date + 60 days
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
//[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// [eventDict objectForKey:@"begin_at"] gives date string like this "2012-04-14T16:50:02Z" for ex.
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:@"begin_at"]];
NSTimeInterval nowSinceEventDate = [eventdate timeIntervalSince1970];
NSLog(@"nowSinceEventDate: %f", nowSinceEventDate);
double eventDateInMilliSecs = nowSinceEventDate * 1000;
NSLog(@"eventDateInMilliSecs: %f", eventDateInMilliSecs);
// this is not working as expected
if ( eventDateInMilliSecs<sixtyDaysMilliSecsFromCurrDate && eventDateInMilliSecs>currDateInMilliSecs )
{
}
else
{
}
答案 0 :(得分:2)
你正试图解决这个问题,好像它是Java,但事实并非如此。相反,尝试使用Cocoa Touch框架中的东西。由于您的计算相当简单,您可以使用日期进行计算,但使用NSCalendar和NSDateComponents可以很容易地完成更复杂的事情。
问题的简单解决方案(此处我们假设eventdate
是您使用格式化程序创建的日期):
NSDate* now = [NSDate date];
NSDate* sixtyDaysFromNow = [now dateByAddingTimeInterval:(60 * 60 * 24 * 60)];
if( [eventDate earlierDate:now] == now && [eventDate laterDate:sixtyDaysFromNow] == sixtyDaysFromNow ) {
// the event date is within scope
} else {
// the event date is outside stop
}
答案 1 :(得分:0)
使用我的函数来比较日期对项目的影响
我希望它可以帮助你
-(BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endingDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endingDate] == NSOrderedDescending)
return NO;
return YES;
}