Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and subtracting time with tm

Tags:

c++

time

time-t

So say I set a time in tm to be 23:00:00

ptm->tm_hour = 23; ptm->tm_min = 0; ptm->tm_sec = 0;

And I want to allow a user to subtract time from this

ptm->tm_hour -= hourinput; ptm->tm_min -= minuteinput; ptm->tm_sec -= secondinput;

If the user subtracts 0 hours, 5 minutes, and 5 seconds, instead of showing up as 22:54:55, it will show up as 23:-5:-5.

I suppose I could do a bunch of if statements to check if ptm is below 0 and account for this, but is there a more efficient way of getting the proper time?

like image 360
Zevvysan Avatar asked Oct 18 '25 07:10

Zevvysan


1 Answers

Yes, you can use std::mktime for this. It doesn't just convert a std::tm to a std::time_t, it also fixes the tm if some field went out of range. Consider this example where we take the current time and add 1000 seconds.

#include <iostream>
#include <iomanip> // put_time
#include <ctime>

int main(int argc, char **argv) {
    std::time_t t = std::time(nullptr);
    std::tm tm = *std::localtime(&t);
    std::cout << "Time: " << std::put_time(&tm, "%c %Z") << std::endl;
    tm.tm_sec += 1000; // the seconds are now out of range
    //std::cout << "Time in 1000 sec" << std::put_time(&tm, "%c %Z") << std::endl; this would crash!
    std::mktime(&tm); // also returns a time_t, but we don't need that here
    std::cout << "Time in 1000 sec: " << std::put_time(&tm, "%c %Z") << std::endl;
    return 0;
}

My Output:

Time: 01/24/19 09:26:46 W. Europe Standard Time

Time in 1000 sec: 01/24/19 09:43:26 W. Europe Standard Time

As you can see, the time went from 09:26:46 to 09:43:26.

like image 133
Blaze Avatar answered Oct 20 '25 23:10

Blaze