iPhone:比较当前日期和当前日期之间的六十天之间的日期时出现问题 [英] iPhone: Issue comparing a date between current date and sixty days from current date

查看:63
本文介绍了iPhone:比较当前日期和当前日期之间的六十天之间的日期时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查活动日期,该日期应该在当前日期和现在之间的60天之间.使用下面的代码,但不能正常工作.请注意,我正在从服务器获取这样的事件字符串-"2012-04-14T16:50:02Z".

I need to check an event date, which should be between Current date and 60 days from now. The below code is used, but it is NOT working correctly. Please note, i'm getting event string like this - "2012-04-14T16:50:02Z" from my server.

    // 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
{
}

推荐答案

您正试图解决它,就好像它是Java,不是.而是尝试使用Cocoa Touch框架中的功能.由于您的计算非常简单,因此可以使用日期进行计算,但是使用NSCalendar和NSDateComponents可以轻松完成更复杂的事情.

You're trying to solve this as if it were Java, which it's not. Instead, try using things from the Cocoa Touch frameworks. Since your calculations are rather simple, you can do them with dates, but more complex things can pretty easily be done using NSCalendar and NSDateComponents.

一个简单的解决方案(此处假设 eventdate 是您使用格式化程序创建的日期):

A simple solution to your problem (here we assume eventdate is the date you created using your formatter):

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
}

这篇关于iPhone:比较当前日期和当前日期之间的六十天之间的日期时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆