NSTimeInterval time = [[NSDate date] timeIntervalSince1970]; 可以这样定义
NSLog(@"当前时间为%f", time); 打印出从1970年开始到现在的秒数。
可见time可以赋值给float类型
所以可以这样写:
float a = time;
这样就可以很容易的到两个时间点中间相差多少秒。
第一种方式:
NSTimeInterval time = 。。。;
NSString *string = [NSString stringWithFormat:@"%02li:%02li:%02li",
lround(floor(time / 3600。)) % 100,
lround(floor(time / 60。)) % 60,
lround(floor(time。)) % 60];
第二种方式:
// You could also have stored the start time using
// CFAbsoluteTimeGetCurrent()
NSTimeInterval elapsedTime = [startDate timeIntervalSinceNow];
// Divide the interval by 3600 and keep the quotient and remainder
p_t h = p(elapsedTime, 3600);
int hours = h。quot;
// Divide the remainder by 60; the quotient is minutes, the remainder
// is seconds。
p_t m = p(h。rem, 60);
int minutes = m。quot;
int seconds = m。rem;
// If you want to get the inpidual digits of the units, use p again
// with a pisor of 10。
NSLog(@"%d:%d:%d", hours, minutes, seconds)
如果您有您初始日期存储在 NSDate 对象时,您可以获得新日期任何时间间隔在未来。只需使用 dateByAddingTimeInterval: 像这样:
NSDate * originalDate = [NSDate date];
NSTimeInterval interval = 1;
NSDate * futureDate = [originalDate dateByAddingTimeInterval:interval];
ios获取自1970年以来的毫秒数同java的System。currentTimeMillis()
示例代码
// The time interval
NSTimeInterval theTimeInterval = 326。4;
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];
NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);
[date1 release];
[date2 release];