Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Simply put, is this function a correct and safe way to add and/or subtract time to a tm struct (from <time.h>)?

void AddTime(int seconds, tm *date)
    date->tm_sec += seconds;

seconds could be any value, supposedly larger than 60 (or smaller than -60). I'm using mktime to readjust the other values in tm, but I don't know if that's right.

I'm also not taking into account going below 1970 or above 3001 for the year, which I think are the default bounds for mktime to operate. I can check for that elsewhere.

share|improve this question
up vote 4 down vote accepted

I would add a sanity check on the pointer as well:

void AddTime(int seconds, tm* date) {
    if (date == NULL) return;
    date->tm_sec += seconds;

But other than that it looks correct.

Reading some documentation on mktime, this appears to be what it was meant for.

share|improve this answer

You should put more validations. For example, if you add more than 60 seconds, you need to increment minutes too. If the minutes value is 59, you must increment hours too.

share|improve this answer
I thought mktime distributed the overflows accordingly. Does it not? – MPelletier Nov 29 '12 at 13:59
mktime does perform normalization on its values – seand Nov 29 '12 at 16:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.