2011-01-20 81 views
3

我想將昨天的日期變成一個格式爲:YYYYMMDD(沒有斜槓點等)的字符。如何在C中獲取昨天的日期?

我使用這個代碼來獲得今天的日期:使其產生昨天的日期,而不是今天的

time_t now; 

struct tm *ts; 
char yearchar[80]; 

now = time(NULL); 
ts = localtime(&now); 

strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts); 

我將如何適應這個代碼?

很多謝謝。

+0

你可能想你的時間轉換一個tm結構體,這樣你可以明確地控制小時,分鐘等。我們通常需要昨天的午夜而不是24小時前,等等(例如:http://www.cplusplus.com/reference/clibrary/ctime/localtime/) – 2011-01-20 15:39:12

+1

@sbi:虛擬-1他不想要標點符號,所以正確的回答是`20110119` :-) – JeremyP 2011-01-20 18:00:21

回答

5

如何添加

now = now - (60 * 60 * 24) 

在一些非常罕見的極端情況可能會失敗(例如在leapseconds),但應該做你想要什麼的時候99.999999%。

+1

這將在1970年1月1日發生可怕的破裂,但我沒有看到它今天會有什麼理由:) – 2011-01-20 15:29:21

2

只需從time(NULL);減去一天的時間就可以了。改變這一行:

now = time(NULL); 

這樣:

now = time(NULL) - (24 * 60 * 60); 
0

你是非常接近的。首先,泰勒的解決方案將差不多工作 - 你需要使用(24*60*60*1000)因爲時間(3)返回毫秒。但看看那struct tm。它包含日期所有組件的字段。

更新:該死,我的錯誤 - 時間(3)確實會返回秒。我在想另一個電話。但無論如何請看struct tm的內容。

0

在將其傳遞到strftime之前,您可以操縱ts結構的內容。該月份的日期包含在tm_mday成員中。基本步驟:

/** 
* If today is the 1st, subtract 1 from the month 
* and set the day to the last day of the previous month 
*/ 
if (ts->tm_mday == 1) 
{ 
    /** 
    * If today is Jan 1st, subtract 1 from the year and set 
    * the month to Dec. 
    */ 
    if (ts->tm_mon == 0) 
    { 
    ts->tm_year--; 
    ts->tm_mon = 11; 
    } 
    else 
    { 
    ts->tm_mon--; 
    } 

    /** 
    * Figure out the last day of the previous month. 
    */ 
    if (ts->tm_mon == 1) 
    { 
    /** 
    * If the previous month is Feb, then we need to check 
    * for leap year. 
    */ 
    if (ts->tm_year % 4 == 0 && ts->tm_year % 400 == 0) 
     ts->tm_mday = 29; 
    else 
     ts->tm_mday = 28; 
    } 
    else 
    { 
    /** 
    * It's either the 30th or the 31st 
    */ 
    switch(ts->tm_mon) 
    { 
     case 0: case 2: case 4: case 6: case 7: case 9: case 11: 
     ts->tm_mday = 31; 
     break; 

     default: 
     ts->tm_mday = 30; 
    } 
    } 
} 
else 
{ 
    ts->tm_mday--; 
} 

編輯:是的,每月的天數從1編號,而所有其他(秒,分鐘,小時,工作日,並在今年的天數)從0

0
time_t now; 
int day; 

struct tm *ts; 
char yearchar[80]; 

now = time(NULL); 
ts = localtime(&now); 
day = ts->tm_mday; 

now = now + 10 - 24 * 60 * 60; 
ts = localtime(&now); 
if (day == ts->tm_mday) 
{ 
    now = now - 24 * 60 * 60; 
    ts = localtime(&now); 
} 

strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts); 
編號

也可以使用閏秒。

7

mktime()功能正常化struct tm,你通過它 - 因此,所有你需要做的是這樣的:

now = time(NULL); 
ts = localtime(&now); 
ts->tm_mday--; 
mktime(ts); /* Normalise ts */ 
strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts); 
2

請試試這個代碼

#include <stdlib.h> 
#include <stdio.h> 
#include <time.h> 
#include <string.h> 
  
int main(void) 
{ 
    char yestDt[9]; 
    time_t now = time(NULL); 
    now = now - (24*60*60); 
    struct tm *t = localtime(&now); 
    sprintf(yestDt,"%04d%02d%02d", t->tm_year+1900, t->tm_mday,t->tm_mon+1); 
    printf("Target String: \"%s\"", yestDt); 
    return 0; 
} 
相關問題