HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Adding time to struct tm

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
structtimeadding

Problem

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

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


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.

Solution

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;
    mktime(date);
}


But other than that it looks correct.

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

Code Snippets

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

Context

StackExchange Code Review Q#5089, answer score: 5

Revisions (0)

No revisions yet.