Home > Software design >  How can I convert the day of the year (2017, 365 days) equivalent date December 31 2022, Sunday
How can I convert the day of the year (2017, 365 days) equivalent date December 31 2022, Sunday

Time:01-24

how can i use the c library such as mktime() to convert day to dates such as 2022, 365 will return december 31, 2022 using c

I have constructed a method to grab a users input and check if the day is valid such as a year cannot have 365 days as well as having different vectors of days of the month, day, and leap year but i should by using mktime() instead of having excessive code

CodePudding user response:

One example of how to use std::mktime to handle the proposed problem is written below.

The key to this algorithm is to use std::mktime to convert from the year input to a base year epoch, ie the number of seconds from 1970-01-01 until year-01-01.

Then you add manually the number of seconds until the date you want. Remember leap seconds do not count so just adding 86400, the number of seconds in a day, is correct.

The last step is to convert back from epoch time into a full date.

#include <ctime>
#include <cstring>
#include <cstdio>

struct YearDay {
    int year;
    int month;
    int day;
};

YearDay convert( int year, int yday ) {
    // Convert year to epoch
    struct tm tms;
    std::memset(&tms,0,sizeof(tms));
    tms.tm_year = year - 1900;
    std::time_t date = std::mktime(&tms);

    // add days manually
    date  = yday * 86400;

    // Synthesize into a full date
    struct tm* newtm = std::gmtime( &date );
    return YearDay{newtm->tm_year 1900, 
                   newtm->tm_mon 1, 
                   newtm->tm_mday};    
}

One example of usage would be:

int main() {
    int year = 2022;
    for ( int yday = 1; yday<=365;   yday ) {
    YearDay yd = convert( year, yday );
    printf( "M %-3d  ==> M-d-d\n",
            year, yday, yd.year, yd.month, yd.day  );
    }
}

Produces when run:

Program stdout
2022 1    ==> 2022-01-01
2022 2    ==> 2022-01-02
2022 3    ==> 2022-01-03
...
2022 363  ==> 2022-12-29
2022 364  ==> 2022-12-30
2022 365  ==> 2022-12-31

Godbolt: https://godbolt.org/z/YvGsoenbK

CodePudding user response:

Mktime is not C , but a C library function. And honestly, it's pretty terrible. The fact that you're even mentioning it might point to you reading outdated material. Also, it's serving a different purpose than what to seem to think it does, but that is of no consequence here:

C has std::chrono. And that allows you to do something like create a date-representing object that describes the beginning of a year, and then add a time delta, i.e., a std::duration (e.g. 365 days or 10⁶ seconds) to it, then convert it to whatever readable representation you need.

You should have actually stumbled across it! Documentation is ample and readily available.

  • Related