How to find Time Duration between two dates with Hours minutes and seconds in C++ 11?

761 Views Asked by At

I need to find the time difference between two given dates.

I have tried the following code but not able to convert it into hours mins secs

         const char *time_details = "06/10/2021 16:35:12";
struct tm tm;
strptime(time_details, "%m/%d/%Y %H:%M:%S", &tm); // Prev date

time_t t = mktime(&tm);

const char *time_details1 = "06/11/2021 14:35:12";
struct tm tm1;
strptime(time_details1, "%m/%d/%Y %H:%M:%S", &tm1); // future date

time_t t33 = mktime(&tm1);

int timediff1 = difftime(t33,t);

    int seconds1 = timediff1%60;
int hour1 =seconds1/ 3600;
int minutes1 = seconds1 / 60 ;

The above always shows '0' in hours mins seconds. But getting some value in

2

There are 2 best solutions below

0
Vicky Web developer On

Try This

void computeTimeDiff(struct TIME t1, struct TIME t2, struct TIME *difference){
    
    if(t2.seconds > t1.seconds)
    {
        --t1.minutes;
        t1.seconds += 60;
    }

    difference->seconds = t1.seconds - t2.seconds;
    if(t2.minutes > t1.minutes)
    {
        --t1.hours;
        t1.minutes += 60;
    }
    difference->minutes = t1.minutes-t2.minutes;
    difference->hours = t1.hours-t2.hours;
}
0
Swift - Friday Pie On

With C++2a early support you can do something like this

std::tm tm1 = {}, tm2 = {};

std::stringstream ss("06/10/2021 16:35:12 06/11/2021 14:35:12");

ss >> std::get_time(&tm1, "%m/%d/%Y %H:%M:%S");
ss >> std::get_time(&tm2, "%m/%d/%Y %H:%M:%S");
auto tp1 = std::chrono::system_clock::from_time_t(std::mktime(&tm1));
auto tp2 = std::chrono::system_clock::from_time_t(std::mktime(&tm2));
auto diff = tp2 - tp1;

// convert to human-readable form
auto d = std::chrono::duration_cast<std::chrono::days>(diff);
diff -= d;
auto h = std::chrono::duration_cast<std::chrono::hours>(diff);
diff -= h;
auto m = std::chrono::duration_cast<std::chrono::minutes>(diff);
diff -= m;
auto s = std::chrono::duration_cast<std::chrono::seconds>(diff);

std::cout << std::setw(2) << d.count() << "d:"
   << std::setw(2) << h.count() << "h:"
   << std::setw(2) << m.count() << "m:"
   << std::setw(2) << s.count() << 's';

And full support offers operator<< for duration class. For C++11 std::chrono::days and hours must be replaced by equivalents, e.g. duration<int, std::ratio<86400>> for days.