2017-03-02 85 views
2

我想獲得ISO8601周編號C. MinGW安裝在我的電腦上。 GCC版本是5.3.0。你可以在下面看到我的代碼。 strftime對說明符「%V」不起作用。但它與指定符「%W」正常工作。但那不是我想要的。我需要ISO 8601格式的每週數字。ISO 8601周編號在C

我試過我的代碼與2不同的在線C編譯器,他們都工作得很好。我懷疑我的電腦上的編譯器配置不當。誰能告訴我我做錯了什麼?任何幫助,將不勝感激。

這裏是我的代碼:

#include <stdio.h> 
#include <time.h> 
#include <string.h> 

int main() 
{ 
    time_t timep; 
    struct tm * time_inf; 
    char buff [80]; 

    time (&timep); 
    time_inf = localtime (&timep); 

    time_inf->tm_year = 2008 - 1900; 
    time_inf->tm_mon = 11; 
    time_inf->tm_mday = 31; 

    mktime (time_inf); 

    strftime (buff, sizeof(buff), "%V", time_inf) ; 
    puts (buff); //prints nothing 

    printf("%d", strlen(buff)); //prints 0 

    return 0; 
} 
+0

你的代碼適合我 - [點擊](http://coliru.stacked-crooked.com/a/af8765f61e764251)。請注意,'%V'格式說明符是語言環境相關的。嘗試挖掘這個,因爲代碼看起來很好 - *除了C不是C++ *。 – mpiatek

回答

2

獲得ISO8601星期數以C

"%V"strftime()不可用或有問題,代碼可以指向計算ISO 8601星期。


ISO 8601週年的開始在星期一。

當想要找到年份的ISO 8601 week時,通常也需要相應的「年份」。

本年第一週,第一週是從星期一開始的第一週,在一月至少有四天 - 或者如下面的代碼所示,第一週是第一週。

可能是12月31日是在明年的第1周。
可能是1月1日在前一年的52/53周。

#include <time.h> 

// return 1 on failure, 0 on success 
int tm_YearWeek(const struct tm *tmptr, int *year, int *week) { 
    // work with local copy 
    struct tm tm = *tmptr; 
    // fully populate the yday and wday fields. 
    if (mktime(&tm) == -1) { 
    return 1; 
    } 

    // Find day-of-the-week: 0 to 6. 
    // Week starts on Monday per ISO 8601 
    // 0 <= DayOfTheWeek <= 6, Monday, Tuesday ... Sunday 
    int DayOfTheWeek = (tm.tm_wday + (7 - 1)) % 7; 

    // Offset the month day to the Monday of the week. 
    tm.tm_mday -= DayOfTheWeek; 
    // Offset the month day to the mid-week (Thursday) of the week, 3 days later. 
    tm.tm_mday += 3; 
    // Re-evaluate tm_year and tm_yday (local time) 
    if (mktime(&tm) == -1) { 
    return 1; 
    } 

    *year = tm.tm_year + 1900; 
    // Convert yday to week of the year, stating with 1. 
    *week = tm.tm_yday/7 + 1; 
    return 0; 
} 

int main() { 
    struct tm tm = { 0 }; 
    tm.tm_year = 2008 - 1900; 
    tm.tm_mon = 12 - 1; 
    tm.tm_mday = 31; 
    tm.tm_isdst = -1; 
    int y = 0, w = 0; 
    int err = tm_YearWeek(&tm, &y, &w); 
    printf("Err:%d Year:%d Week:%d %02d%02d\n", err, y, w, y%100, w); 
    return 0; 
} 

輸出是2009年的1周2008年12月31日或0901 。這可以通過上述討論來預料,並且可以解釋OP對OP代碼的未說明的關注。

Err:0 Year:2009 Week:1 0901 
+1

儘管我用一些代碼計算了ISO 8601星期,但您的代碼更好,更短。我會切換到這一個。非常感謝。 –