如何获得小时数的日期差异?

时间:2011-06-30 10:02:33

标签: iphone

我有一个来自数据库的日期,在2011-11-30 18:38:00 +0000这个格式,我需要从现在起日期差异。如何可能?我正在做的事情: -

  NSDate* pDateEnd;



  NSLog(@"PDateEnd=%@",pDateEnd); //it has value=2011-11-30 18:38:00 +0000

NSTimeInterval secForDeal = [pDateEnd timeIntervalSinceNow];

NSLog(@"secForDeal=%i",secForDeal);
if(secForDeal < 0)
    return nil;
//////
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];

NSDateComponents* pRemainingDate = [[[NSDateComponents alloc] init] autorelease];

[pRemainingDate setHour:0];

[pRemainingDate setMinute:0];

[pRemainingDate setSecond:secForDeal];

//preparing date 
NSDate *date = [currentCalendar dateFromComponents:pRemainingDate];
//again splitting date to components
NSDateComponents *comps = [currentCalendar components:unitFlags fromDate:date];
/////Generating the date
NSString* pRetTimeRemaining = [NSString stringWithFormat:@"%i Year %i Month %i days %i Hr %i Min",[comps year],[comps month],[comps day],[comps hour],[comps minute]];
///////
NSLog(@"pRetTimeRemaining=%@",pRetTimeRemaining);
return pRetTimeRemaining;

请告诉我是否有任何错误或其他方法。谢谢。

2 个答案:

答案 0 :(得分:2)

尝试使用以下代码获取两个日期之间的天数,分钟数,小时数。

// The time interval 
NSTimeInterval theTimeInterval = 326.4;

// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];

// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1]; 

// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);

[date1 release];
[date2 release];

请尝试使用以下代码获取两个日期之间的天数。

-(int)howManyDaysHavePast:(NSDate*)lastDate today:(NSDate*)today {
    NSDate *startDate = lastDate;
    NSDate *endDate = today;
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned int unitFlags = NSDayCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags
                                                fromDate:startDate
                                                  toDate:endDate options:0];
    int days = [components day];
    return days; // multiply by 24 for get remain hrs.
}

或者fololw

答案 1 :(得分:2)

您可以从代码下方获取一小时。

int interval = [invoiceDate timeIntervalSinceDate:date];
int hour = interval/3600;