两个nsdates之间的时差

时间:2013-12-11 07:46:47

标签: ios objective-c xcode nsdate

我的目标是制作一个倒计时标签。所以,例如,我想显示时间19:00:00和当前时间之间的差异。我已经为它编写了一个代码。 另外,我已经使用sqlite存储了一段时间; 19时00分00秒。

    //start time
    NSString *starttime = mission.starttime;
    NSDate *starttime_convert;
    NSDateFormatter *formatttter = [[NSDateFormatter alloc]init];
    [formatttter setDateFormat:@"HH:mm:ss"];
    starttime_convert = [formatttter dateFromString:starttime];

    //current time
    NSDate *nowtime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMT]];
    //NSLog(@"Current Time %@", nowtime);

    float countdown = [nowtime timeIntervalSinceDate:starttime_convert];
    int hh = (countdown/3600);
    NSLog(@"%d",hh);
    int mm = ((countdown-(hh*3600))/60);
    int ss = countdown-(hh*3600+mm*60);
    NSLog(@"%02d:%02d:%02d",hh,mm,ss);

然而,将显示的结果是,122238:43:32。 因为,当前时间是16:44:32,应该显示02:15:68。但事实并非如此。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您应该在开始时间指定当前日期,而不是仅指定@"19:00:00"

为此,您可以使用以下代码:

NSString *starttime = @"19:00:00";
NSArray *times = [starttime componentsSeparatedByString:@":"];

int hour = [times[0] integerValue];
int minute = [times[1] integerValue];
int second = [times[2] integerValue];

NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: hour];
[components setMinute: minute];
[components setSecond: second];

NSDate *starttime_convert = [gregorian dateFromComponents: components];

//current time
//NSDate *nowtime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMT]];
float countdown = -[date timeIntervalSinceDate:starttime_convert];//pay attention here.
int hh = (countdown/3600);
NSLog(@"%d",hh);
int mm = ((countdown-(hh*3600))/60);
int ss = countdown-(hh*3600+mm*60);
NSLog(@"%02d:%02d:%02d",hh,mm,ss);

答案 1 :(得分:0)

self.startTime = [[NSDate date] timeIntervalSince1970];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];


- (void)startTimer {
    double difference = [[NSDate date] timeIntervalSince1970] - self.startTime;
    int hh = 0, mm = 0, ss = 0;
    if(difference < 60) {
        ss = difference;
    } else if(difference/60 < 60) {
        mm = difference/60;
        ss = difference%60;
    } else if(difference/3600 < 24) {
        mm = difference/60;
        hh = mm/60;
        mm = mm%60;
        ss = difference%3600;
    }
    NSLog(@"%2d:%2d:%2d", hh, mm, ss);
}

我已经检查了几分钟和几秒钟,工作正常。我认为它也会工作几个小时。