NSTimeInterval的使用

本文介绍了两种在iOS开发中处理时间间隔的方法,包括如何将时间间隔转换为标准的时间格式字符串,以及如何通过NSDate对象来获取未来时间点的具体日期。
第一种方式: 
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 
    div_t h = div(elapsedTime, 3600); 
    int hours = h.quot; 
    // Divide the remainder by 60; the quotient is minutes, the remainder 
    // is seconds. 
    div_t m = div(h.rem, 60); 
    int minutes = m.quot; 
    int seconds = m.rem; 

    // If you want to get the individual digits of the units, use div again 
    // with a divisor 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() 

Java代码  收藏代码
  1. + (NSString*)generateTimeIntervalWithTimeZone  
  2. {  
  3.     NSMutableString *result = [[NSMutableString alloc] init];  
  4.     NSDate *date = [NSDate date];  
  5.     NSTimeInterval time = [date timeIntervalSince1970]*1000;//毫秒数要乘以1000  
  6.     double i=time;      //NSTimeInterval返回的是double类型  
  7.       
  8.       
  9.     NSDateFormatter *format = [[NSDateFormatter alloc] init];  
  10.     [format setDateFormat:@"Z"];  
  11.     NSString *timeZone = [format stringFromDate:date];  
  12.     NSString *timeIntervalStr = [NSString stringWithFormat:@"%.f", i];  
  13.       
  14.     [result appendString:timeIntervalStr];  
  15.     [result appendString:timeZone];  
  16.       
  17.     return result;  
  18. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值