objective-c 如何获取 iPhone 中的时差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1427151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:12:39  来源:igfitidea点击:

How to Get time difference in iPhone

iphoneobjective-cnsdatenstimeinterval

提问by New to iPhone

I have 2 arrays with time values in it. They are in the following format. mm:ss:hundreds of a sec. I want to get the difference between the two [lastObjects] in the arrays. NSDate is not working because the last value is in hundredsth of a sec.

我有 2 个带有时间值的数组。它们采用以下格式。mm:ss:数百秒。我想获得数组中两个 [lastObjects] 之间的差异。NSDate 不起作用,因为最后一个值是百分之一秒。

A question. If the second date is larger than the first will it give me a negative number like -01:10:00 ?

一个问题。如果第二个日期大于第一个日期,它会给我一个像 -01:10:00 这样的负数吗?

回答by Nathan de Vries

Your problem has two parts, parsing the time and getting the difference:

您的问题有两个部分,解析时间并获取差异:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:@"mm:ss:SS"];

NSDate* firstDate = [dateFormatter dateFromString:@"01:00:00"];
NSDate* secondDate = [dateFormatter dateFromString:@"01:02:00"];

NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];

回答by Daniel

NSDateshould work for you, use timeIntervalSinceDate:, which returns a time interval which has millisecond precision.

NSDate应该对你有用,使用timeIntervalSinceDate:,它返回一个具有毫秒精度的时间间隔。