When using time()
, Is there any other way besides adding seconds?
When adding/subtracting you need to use the same unit, seconds here (you do not just count the number of the various different coins in your pocket to see how much money you have, don't you?)
If too lazy to calculate the number of second in a minute, hour, day you might code the create some functions or macros to do so:
#define SECONDS_PER_MINUTES(m) ((m)*60)
#define MINUTES_PER_HOURS(h) ((h)*60)
#define HOURS_PER_DAYS(d) ((d)*24)
You could even reuse those like
#define SECONDS_PER_HOURS(h) (MINUTES_PER_HOURS(h) * SECONDS_PER_MINUTES(1))
#define SECONDS_PER_DAYS(d) (HOURS_PER_DAYS(d) * SECONDS_PER_HOURS(1))
Using the macros above you can add a 2 days to a time returned by time()
like this:
time_t = time(NULL) + SECONDS_PER_DAYS(2);
If you'd pass the above line to the C pre-processor, then you'd see that it gets converted to:
time_t = time(((void *)0)) + (((2)*24) * (((1)*60) * ((1)*60)));
This (((2)*24) * (((1)*60) * ((1)*60))
is a compile time constant and would not be calculated each time you'd ran the code, but just once during compilation.
Note: That NULL
is a macro here a swell, namely:
#define NULL ((void *)0)
For calculating the number of second in a month or year unfortunately it's not the that simple, as the numbers of days per month vary, depending on the month and for February even on the year the month belongs to.
To get around this use two struct tm
initialised to the appropriate date/time and pass them to mktime()
to receive the related time in seconds (since EPOCH).
Then use difftime()
to calculate the difference.
struct tm d1 = {0};
struct tm d2 = {0};
d1.tm_day = 1; /* day of month */
d1.tm_mon = 0; /* month - 1 */
d1.tm_year = 113 /* to specify 2013 == 1900+113 */
d2.tm_day = 1; /* day of month */
d2.tm_mon = 0; /* month - 1 */
d2.tm_year = 114 /* to specify 2014 == 1900+114 */
time_t t1 = mktime(d1);
time_t t2 = mktime(d2);
double d = difftime(d2, d1); /* number of seconds of year 2013. */