我想为iOS编写闹钟。
我的计算当前时间和闹钟时间之间差异的代码:
NSDate *date = picker.date;
NSLog(@"[date description] %@",[date description]);
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"HH:mm:ss"]; //24h time format
NSString *dateString = [outputFormatter stringFromDate:picker.date];
NSLog(@"[date description] %@",dateString);
NSDate *startDate = [outputFormatter dateFromString:dateString];
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDate *endDate = [dateFormatter dateFromString:resultString];
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate];
double minutes = timeDifference / 60;
double hours = minutes / 60;
double seconds = timeDifference;
...导致这些变量:
startDate = 2000-01-01 06:45:26 +0000
endDate = 2000-01-01 22:46:36 +0000
seconds = 57670 (= 16.01944 hours).
如何计算28740秒的实时差异?
答案 0 :(得分:0)
在下面的方法中传递timeDifference。它会给你几小时,几分钟和几秒钟。
- (NSString *)timeFormatted:(int)totalSeconds{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return hours==0 ? [NSString stringWithFormat:@"%02d:%02d", minutes, seconds] : [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}
答案 1 :(得分:0)
尝试以下代码:
获取NSTimeInterval
小时,分钟,秒的时差:
//.......
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate];
long ti = lroundf(timeInterval);
int hour = ti / 3600;
int mins = (ti % 3600) / 60;
int secs = ti % 60;
或
从日期获取小时,分钟,秒的时差:
// Get the system calendar
NSCalendar *objCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *currentTime = [[NSDate alloc] init];
NSDate *startDate = picker.date;
// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *TimeInfo = [objCalendar components:unitFlags fromDate: currentTime toDate:startDate options:0];
NSLog(@" %dmin %dhours %ddays %dmoths ",[TimeInfo minute], [TimeInfo hour], [TimeInfo day], [TimeInfo month]);