Search code examples
cstrptime

How to set current year in strptime in C


I wonder how I can set the current year in strptime, only if it hasn't been set in the input character string.

#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;
}

Solution

  • It's probably simplest to use time() and localtime() to get the year value, and then transfer that into the structure populated by 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;
    }