如何才能正确找到此代码中的时差?

时间:2011-06-15 15:15:01

标签: objective-c ios xcode

我试图将当前时间与时间10:15进行比较,然后找出差异即。分钟一直持续到10:15。一切都汇编,但我总是得到75 ....有人可以帮忙吗?如果可能的话,我真的很喜欢编码示例。我也尝试使用 - (时间间隔)timeIntervalSinceNow,但我无法弄清楚如何工作,所以如果有人也有解释,我会非常感激 *注意我使用的是版本3.2.6,请相应提出建议,谢谢

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                                   initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =
[gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];

NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];


NSInteger combo = hour + (minute/60) + (second/3600);

NSTimeInterval time = combo*60*60;

NSTimeInterval tenFifteenFirstPeriodStop = 10.25*60*60;

    double myDouble;
int myInt;
NSString* myNewString;
NSString *info;



           if(time <tenFifteenFirstPeriodStop){
         myDouble = (tenFifteenFirstPeriodStop-time)/60;
         myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5));
         myNewString = [NSString stringWithFormat:@"%d", myInt];
         info = [[NSString alloc] initWithFormat:
         @"%@",myNewString];
         }

             NSString *message = [[NSString alloc] initWithFormat:
                     @"%@", info];

  UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Minutes Until the Bell            Rings" message:message delegate:nil cancelButtonTitle:@"Great!" otherButtonTitles:nil];
[alert show];
[alert release];
[message release];

1 个答案:

答案 0 :(得分:0)

这将为您提供到今天10月15日的时间。如果它已经过去了,它将显示明天10点15分的时间。

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
                                            fromDate:today];
[components setMinute:15];
[components setHour:10];

NSDate * tenFifteenToday = [gregorian dateFromComponents:components];
if ( [tenFifteenToday timeIntervalSinceNow]  < 0 ) {
    NSDateComponents * daysToAdd = [[[NSDateComponents alloc] init] autorelease];
    [daysToAdd setDay:1];

    NSDate * tenFifteenTomorrow = [gregorian dateByAddingComponents:daysToAdd toDate:tenFifteenToday options:0];
    NSLog(@"%.0lf", [tenFifteenTomorrow timeIntervalSinceNow]);
} else {
    NSLog(@"%.0lf", [tenFifteenToday timeIntervalSinceNow]);
}