Measuring time difference efficently?

I have accomplished this but it looks hacky if you ask me

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
time_t timeToNextFeed()
{
    Leaf::Record* r = records->getRecord(0);
    if (r != NULL)
    {
        time_t lastFed = r->getColumn("FED_DATETIME")->data.datal;
        time_t nextFeed = (lastFed + (60 * 60 * 24 * 6));
        time_t timeNow = time(NULL);
        double timeToNxtFeed = (nextFeed - timeNow);
        return timeToNxtFeed;
    }

    return 0;
}

void nextFeed()
{
    HWND nxtFeed_Lbl;
    std::stringstream ss;
    time_t timeToNxtFeed;
    time_t feedOn;
    timeToNxtFeed = timeToNextFeed();
    feedOn = timeToNextFeed() + time(NULL);
    /* This code below is a bit hacky and I am pretty sure their are easier ways of doing it
     * but I spent long enough on trying to accomplish this. Feel free to fix it up if you want.*/
    int days = timeToNxtFeed / 60 / 60 / 24;
    int hours = ((timeToNxtFeed - days * 60 * 60 * 24) / 60 / 60);
    ss << "Next feed: " << days << " days and " << hours << " hours" << endl;
    ss << "Feed on: " << Misc::timeString("%d/%m/%Y %X", feedOn);
    nxtFeed_Lbl = GetDlgItem(_hwndDlg, 3);
    SendMessage(nxtFeed_Lbl, WM_SETTEXT, 0, (LPARAM)ss.str().c_str());
}



Do any of you know a better way of doing this please?
bump
That's about it, but I have some comments.

Why is timeToNxtFeed a double on line 9? It should be a time_t
Why are you calling timeToNextFeed() twice (lines 22 and 23)? Line 23 should be
feedOn = timeToNxtFeed + time(NULL);

But really, consider the logic here. timeToNextFeed() computes the time of the next feeding. Then it subtracts time(0) to get the number of seconds until the next feeding. nextFeed() then adds time(0) back in to get the time of the next feeding. It would be better to rename timeToNextFeed() to be timeOfNextFeed() and have it return the actual feed time. This has the added advantage of avoiding the intermittent bug of having time(0) return different values on line 8 and line 23, which could extend the feed time by 1 second.
Topic archived. No new replies allowed.