Search code examples
c++timestructmktimectime

How to get the first Sunday of year in c++?


I tried to get the date of first Sunday in this year

int getFristSunday () {
    time_t rawtime;
    struct tm * timeinfo;
    time( &rawtime );
    timeinfo = localtime( &rawtime );
    timeinfo->tm_mon = 0;
    timeinfo->tm_wday = 0;
    mktime( timeinfo );
    return timeinfo->tm_yday ;
}

but I get the first Thursday

Result


Solution

  • From this mktime reference:

    time->tm_wday and time->tm_yday are ignored.

    You have to set timeinfo->tm_mday to 1 and then check what day it is after calling mktime, and count forward from there.