2014-07-16 33 views
1

我不知道如何設置當前年份strptime,只有在輸入字符串中沒有設置。如何在C中設置當前年份

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

int main() { 
    struct tm tm; 

    char buffer [80]; 
    // year not set, so use current 
    char *str = "29-Jan"; 
    if (strptime (str, "%d-%b", &tm) == NULL) 
     exit(EXIT_FAILURE); 
    if (strftime (buffer,80,"%Y-%m-%d",&tm) == 0) 
     exit(EXIT_FAILURE); 

    // prints 1900-01-29 instead of 2014-01-29 
    printf("%s\n", buffer); 

    return 0; 
} 

回答

1

這可能是最簡單的使用time()localtime()獲得年度值,然後轉移到這一點通過strptime()人口結構。

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

int main(void) 
{ 
    struct tm tm; 
    time_t now = time(0); 
    struct tm *tm_now = localtime(&now); 
    char buffer [80]; 
    char str[] = "29-Jan"; 

    if (strptime(str, "%d-%b", &tm) == NULL) 
     exit(EXIT_FAILURE); 

    tm.tm_year = tm_now->tm_year; 

    if (strftime(buffer, sizeof(buffer), "%Y-%m-%d", &tm) == 0) 
     exit(EXIT_FAILURE); 

    printf("%s\n", buffer); 

    return 0; 
} 
+0

非常簡單。謝謝! – user1024718

相關問題