天天看點

NSTimeInterval的使用

第一種方式: 

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() 

NSTimeInterval的使用

+ (nsstring*)generatetimeintervalwithtimezone  

{  

    nsmutablestring *result = [[nsmutablestring alloc] init];  

    nsdate *date = [nsdate date];  

    nstimeinterval time = [date timeintervalsince1970]*1000;//毫秒數要乘以1000  

    double i=time;      //nstimeinterval傳回的是double類型  

    nsdateformatter *format = [[nsdateformatter alloc] init];  

    [format setdateformat:@"z"];  

    nsstring *timezone = [format stringfromdate:date];  

    nsstring *timeintervalstr = [nsstring stringwithformat:@"%.f", i];  

    [result appendstring:timeintervalstr];  

    [result appendstring:timezone];  

    return result;  

}  

上一篇: 詳解NStimer