Addition some interval to tm structs

后端 未结 4 1198
温柔的废话
温柔的废话 2021-01-04 18:37

I have one struct tm.
And I need to add some fixed interval (given in xx years, xx months, xx days) to the tm struct.
Is there any standard functio

4条回答
  •  攒了一身酷
    2021-01-04 19:11

    The standard addition operator works.

    struct tm x;
    /* add 2 years and 3 days to x */
    x.tm_year += 2;
    x.tm_mday += 3;
    

    Edit: you can easily make a function

    struct tm addinterval(struct tm x, int y, int m, int d) {
        x.tm_year += y;
        x.tm_mon += m;
        x.tm_mday += d;
        mktime(&x); /* normalize result */
        return x;
    }
    

    EDIT: added mktime to normalize result

提交回复
热议问题