Search code examples
ctimestrftimestrptime

strptime to strftime for day of the week


I'm using the following format string with strptime

// Populates input_tm with an input string of Monthname Date, Year
strptime(input_string, "%B %d, %Y", &input_tm);

// Output the day of the week from input_tm
strftime(output_string, TIME_BUFSZ, "%A", &input_tm);

After the call to strftime the output_string contains "?"

What additional fields to I need to populate in input_tm for strftime to work?

Edit:

Figured it out by looking at the source of strftime

The required struct field is tm_wday.

If I set input_tm.tm_wday to something manually before the call to strftime it gives me an output.

So now my question is, is there a standard C function that will compute the weekday from a given date?


Solution

  • This works for me — the call to mktime() resolves the problems you got:

    #include <stdio.h>
    #include <time.h>
    
    enum { TIME_BUFSZ = 256 };
    
    int main(void)
    {
        char input_string[] = "November 18, 2014";
        char output_string[TIME_BUFSZ];
    
        struct tm input_tm = { 0 };
        char *end = strptime(input_string, "%B %d, %Y", &input_tm);
        if (*end != '\0')
            printf("Unused data: [[%s]]\n", end);
    
        printf("tm_year = %d; tm_mon = %d; tm_mday = %d; tm_wday = %d; tm_yday = %d\n",
                input_tm.tm_year, input_tm.tm_mon, input_tm.tm_mday,
                input_tm.tm_wday, input_tm.tm_yday);
        time_t t0 = mktime(&input_tm);
        printf("tm_year = %d; tm_mon = %d; tm_mday = %d; tm_wday = %d; tm_yday = %d\n",
                input_tm.tm_year, input_tm.tm_mon, input_tm.tm_mday,
                input_tm.tm_wday, input_tm.tm_yday);
        printf("t0 = %lld\n", (long long)t0);
    
        size_t nbytes = strftime(output_string, TIME_BUFSZ, "%A", &input_tm);
    
        printf("in: [[%s]]\n", input_string);
        printf("out (%zu): [[%s]]\n", nbytes, output_string);
        return 0;
    }
    

    Example run (GCC 4.8.2 on Mac OS X 10.9.2 Mavericks):

    tm_year = 114; tm_mon = 10; tm_mday = 18; tm_wday = 0; tm_yday = 0
    tm_year = 114; tm_mon = 10; tm_mday = 18; tm_wday = 2; tm_yday = 321
    t0 = 1416297600
    in: [[November 18, 2014]]
    out (7): [[Tuesday]]
    

    This agrees with the result from cal 11 2014:

       November 2014
    Su Mo Tu We Th Fr Sa
                       1
     2  3  4  5  6  7  8
     9 10 11 12 13 14 15
    16 17 18 19 20 21 22
    23 24 25 26 27 28 29
    30