Search code examples
cdatetimemktimelocaltime

localtime() gets it wrong, says date = September 31


I am making a calendar program. The 'expand repeating events' code is giving me no end of trouble. I am expanding events by using mktime() to get a 'pure' time value, then adding the repeat delta (in this case, 604800 seconds or 7 days) to it. localtime() is then used to get a calendar struct back out.

This happens:

Original event: September 10

{tm_sec = 0, tm_min = 0, tm_hour = 16, tm_mday = 10, tm_mon = 9,
 tm_year = 2012, tm_wday = 4, tm_yday = 283, tm_isdst = 0, 
 tm_gmtoff = -25200, tm_zone = 0x608ff0 "PDT"}

First repetition: September 17

{tm_sec = 0, tm_min = 0, tm_hour = 17, tm_mday = 17, tm_mon = 9,
 tm_year = 2012, tm_wday = 4, tm_yday = 290, tm_isdst = 1, 
 tm_gmtoff = -25200, tm_zone = 0x608ff0 "PDT"}

Second repetition: September 24

{tm_sec = 0, tm_min = 0, tm_hour = 16, tm_mday = 24, tm_mon = 9,
 tm_year = 2012, tm_wday = 4, tm_yday = 297, tm_isdst = 0,
 tm_gmtoff = -25200, tm_zone = 0x608ff0 "PDT"}

Third repetition: September 31?!

{tm_sec = 0, tm_min = 0, tm_hour = 16, tm_mday = 31, tm_mon = 9,
 tm_year = 2012, tm_wday = 4, tm_yday = 304, tm_isdst = 0,
 tm_gmtoff = -25200, tm_zone = 0x608ff0 "PDT"}

Does anyone have any idea what's going on here? Will I have to fill in for localtime() myself?


Solution

  • From the documentation: the members of the struct tm structure are 0-based (as usually in C).

    int    tm_mon   month of year [0,11]
    

    So actually the month numbered 9 is the 10th month, which is October, and it has 31 days.