时间计算给出越来越错误的结果

时间:2011-03-25 23:49:51

标签: iphone objective-c cocoa

我需要创建一个从我从服务器获取的字符串倒计时的Timer。字符串输出剩余的总秒数。

我正在使用此代码 - 它会计算正确的初始编号时间,并且会倒计时,但分钟是问题。

编辑 - 分钟计算的每一分钟都会增加一分钟。但我不明白为什么会这样做。

- (void)showTimmer:(id)sender {

//get total amount of seconds

NSString *timeRaw =  [ArrayFromServer objectAtIndex:1];
NSArray *timeArr = [timeRaw componentsSeparatedByString:@","];
timetoInt =  [timeArr objectAtIndex:0];
int time1 = [timetoInt intValue];

//set the second countdown

NSDate* now = [NSDate date];    
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *dateComponents = [gregorian components:(NSSecondCalendarUnit) fromDate:now];

NSInteger seconds = time1 - [dateComponents second];

[gregorian release];

// do the hours days maths

int hour = (seconds / 3600 );
seconds -= hour * 3600;
int minute = (seconds / 60 );
seconds -= minute * 60;
int second = seconds;

//set the labels

countdownLabel.text = [NSString stringWithFormat:@"%02dH %02dM %02ds", hour, minute, second];

2 个答案:

答案 0 :(得分:3)

您需要从进入下一行之前的总秒数中减去计算的小时数(不确定为什么使用模数)。这样的事情(注意

int hour = (seconds / 3600 );
seconds -= hour * 3600;
int minute = (seconds / 60 );
seconds -= minute * 60;
int second = seconds;

希望能解决它。

答案 1 :(得分:1)

你正在用钳子开螺丝。如果您在seconds所代表的时间查看秒针,则NSDateComponents的{​​{1}}方法会为您提供在时钟上看到的内容。例如,当我键入它时,它是UTC 2011年3月26日星期六,02:52:04。如果我获得了NSDate,则将其转换为[NSDate date],并询问其NSDateComponents,我会得到“4”。如果我在一秒钟内再次这样做,我会得到“5”,当分钟点击时,我会得到“59”,然后是“0”。

您可以自己验证;把它放在你的计时器方法中:

seconds

因此,每当实际时钟的分钟结束时,您计算剩余时间:

NSInteger dcSecond = [dateComponents second];
NSLog(@"%d", dcSecond);

NSInteger seconds = time1 - [dateComponents second]; 中减去0并返回time1。这就是你遇到问题的原因。

修复它的方法是转储日历内容并使用time1。首先,将开始时间放在计时器的userInfo中(如果您愿意,可以在ivar中):

CFAbsoluteTimeGetCurrent()

然后更改剩余时间的计算(您调用的变量[NSTimer scheduledTimer... // The function returns CFAbsoluteTime, which is a // typedef'd double but you're already working with // integers, so use a cast userInfo:[NSNumber numberWithInteger:(NSInteger)CFAbsoluteTimeGetCurrent()] ...];

seconds

*:嗯,一种方式,但我认为可能是最好的。

相关问题