2016-09-28 122 views
0

我想獲取從某個日期到當前日期的天數。 這是我現在的代碼,從1970年1月1日開始。使用time()函數獲取日期和時間之間的日期

int days_since_my_birth(int day, int month, int year) { 

    time_t sec; 
    sec = time(NULL); 

    printf("Number of days since birth is %ld \n", sec/86400); 

    return d; 
} 

我可以使用time()函數從我輸入的日期得到的秒數?

+0

1)用'mktime()'將生日轉換爲'time_t'。 (如果在1970年1月1日之前出生,可能會有麻煩)2)用'time()'獲得當前時間3)用'difftime()'獲得差值,然後除以(60 * 60 * 24)。 – chux

+1

'man mktime','man difftime'。 *更新*:好的,@chux獲勝... –

+0

爲什麼''自誕生以來的小時數「'目標是」獲得天數「? – chux

回答

0

這裏是我到底做了些什麼。如果進入的生日是在1970年之前,它不起作用。感謝所有的幫助。

我只是剛開始學習c,所以可能有更有效的方法來做到這一點。

int days_since_my_birth(int day, int month, int year) { 

    //create a time struct and initailize it with the function parameters 
    struct tm time_info = { 0 }; 
    time_info.tm_year = year - 1900; 
    time_info.tm_mon = month -1; 
    time_info.tm_mday = day; 

    //get the number of seconds from 1970 
    int n = time(NULL); 

    // convert the birthdate to seconds 
    double birthday = mktime(&time_info); 
    // convert the birthdate to days 
    birthday = (birthday/86400); 
    //get the no of days alive by subtracting birthdate days 
    int result = (n/86400) - birthday; 

    return result; 

} 
+0

該解決方案容易出現1錯誤,因爲1)'mktime()'輸入對時區敏感,但結果丟棄時區數據並且2)將double向int整理截至0。 '(n/86400) - 生日'計算。在今天的日期試試這個函數,比如'printf(「%d \ n」,days_since_my_birth(2,10,2016)); printf(「%d \ n」,days_since_my_birth(3,10,2016)); printf(「%d \ n」,days_since_my_birth(4,10,2016));'看看你是否得到2或3個不同的結果。根據_your_時區,在午夜前後(UTC時間午夜)試試看另一個問題。 – chux

0

獲取和現在使用的時間()函數

#include <math.h> 
#include <time.h> 
int days_since_my_birth(int day, int month, int year, double *days) { 

    struct tm birthdate = { 0 }; // set all fields to 0 
    birthdate.tm_year = year - 1900; 
    birthdate.tm_mon = month - 1; // Months since January 
    birthdate.tm_mday = day; 
    birthdate.tm_isdst = -1; // Let system determine if DST was in effect 

    // Form timestamp for the birthdate. 
    time_t birth_time = mktime(&birthdate); 
    if (birth_time == -1) return FAIL; 

    time_t now; 
    if (time(&now) == -1) return FAIL; 

    // Calculate difference in seconds and convert to days. 
    // Round as desired (rint(), floor(), etc.) 
    *days = floor(difftime(now, birth_time)/86400); 
    return SUCCESS; 
} 

日期之間的天數我可以用嗎time()函數從我輸入的日期獲取秒數?

也許,time(NULL)不是由C指定的返回秒,也不是自1970年1月1日以來的特定時期 - 儘管這通常是以這種方式實現的。

difftime()以秒爲單位返回差值。

+0

即時嘗試運行您的代碼時,我得到異常我設法弄清楚如何做到這一點我自己我已經添加我的解決方案的線程。請問爲什麼你有*天作爲函數參數,而不是聲明爲局部變量? – Swannie

+0

@Swannie'* days'用於返回活期存活值。該函數的返回值表示成功或失敗。關於「獲得例外」,你是怎麼稱呼這個功能的?像'雙d; if(days_since_my_birth(3,10,2016,&d)== SUCCESS)printf(「%f \ n」,d);'? – chux