我怎么能在iPhone的两个时间之间取得差异?

时间:2013-01-29 08:59:34

标签: iphone ios ipad

我有一个应用程序,其中我需要在tableview中显示一个标签,如Xseconds前和xminutes& yseconds前,X小时前就像那样。我正在这样做`

NSString *todaysdateString=[dict objectForKey:@"sendingtime"];

NSString *time = todaysdateString;
NSString*todaysdateString1=[NSString stringWithString: @" "];

NSDate *date1;
NSDate *date2;
//{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
date1 = [formatter dateFromString:time];
date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
[formatter release];
//}
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];
float seconds = interval;
float hour = interval / 3600;
float minute =(interval - hour*3600) / 60;
NSLog(@"%02.0f,%02.0f,%02.0f",hour, minute, seconds);

`但是这不会给我想要的答案,我变得像-0,00,-297那样完全错了。任何人都可以指出我在哪里出错......

2 个答案:

答案 0 :(得分:1)

使用NSCalendar执行此操作,也许此代码可以帮助您

NSCalendar *c = [NSCalendar currentCalendar];
NSDateComponents *components = [c components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
                                    fromDate:initialDate
                                      toDate:endDate
                                     options:0];

components变量中,您将获得差异,请使用:components.daycomponents.minutecomponents.second

答案 1 :(得分:0)

由于你的秒数是负数,你应该在这里交换日期

NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];

到:

NSTimeInterval interval = [date2 timeIntervalSinceDate: date1];

可以这样做:

NSInteger intervalInt=interval;

NSInteger seconds = intervalInt % 60;
NSInteger minutes = (intervalInt / 60) % 60;
NSInteger hours = intervalInt / (60 * 60);
NSString *result = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minutes, seconds];