Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition some interval to tm structs

Tags:

c

time-t

ctime

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 function to do this?

The compiler I use is MSVC 2005 on Windows XP.

like image 706
StNickolay Avatar asked Nov 18 '10 11:11

StNickolay


People also ask

What is struct tm in C++?

The structure type tm holds the date and time in the form of a C structure having the following elements − struct tm { int tm_sec; // seconds of minutes from 0 to 61 int tm_min; // minutes of hour from 0 to 59 int tm_hour; // hours of day from 0 to 24 int tm_mday; // day of month from 1 to 31 int tm_mon; // month of ...

What is Mktime in C?

The mktime() is an inbuilt C++ function which converts the local calendar time to the time since epoch and returns the value as an object of type time_t.


1 Answers

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

like image 190
pmg Avatar answered Oct 10 '22 06:10

pmg