2010-08-02 29 views
4

我有一個日期字符串格式說,如「2010-03-01」,以tm_wday,我想它的「tm_wday」相當於說喜歡週一,週二......如何轉換日期字符串在TM結構

可能有人給我如何在C++實現這個提示嗎?

回答

3

檢查strptime()功能:

​​

的strptime()函數是相反的功能,以strftime(3)並轉換 字符串指向s到被存儲在TM結構 尖值由TM,使用由格式中指定的格式。

1

使用mktime()計算工作日。

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

int main(void) { 
    const char *p = "2010-03-01"; 
    struct tm t; 
    memset(&t, 0, sizeof t); // set all fields to 0 
    if (3 != sscanf(p,"%d-%d-%d", &t.tm_year, &t.tm_mon, &t.tm_mday)) { 
    ; // handle error; 
    } 
    // Adjust to struct tm references 
    t.tm_year -= 1900; 
    t.tm_mon--; 
    // Calling mktime will set the value of tm_wday 
    if (mktime(&t) < 0) { 
    ; // handle error; 
    } 
    printf("DOW(%s):%d (0=Sunday, 1=Monday, ...)\n", p, t.tm_wday); 
    // DOW(2010-03-01):1 (0=Sunday, 1=Monday, ...) 
    return 0; 
}