如何在C中设置当前年份

时间:2014-07-16 00:24:39

标签: c strptime

我想知道如何在strptime中设置当前年份,只有在输入字符串中没有设置它。

#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 个答案:

答案 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;
}