Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and Subtracting Time

Tags:

c++

time

I am new to C++ - I wanted to make a program to add and subtract time using a HH:MM format. Sample Input:

12:00 + 3:00 - 6:00

Sample Output:

9:00

Another Sample Input:

9:00 + 8:00 + 13:00 - 2:25

Sample Output:

27:35

How do I got about this? I was thinking convert everything down to seconds and then apply the math then use a modulus 60 function to return the time. Any help on building such a program?

like image 784
Emptypeace Avatar asked Dec 22 '12 04:12

Emptypeace


People also ask

What is the time 15 hours before 11pm?

Hence, the time 15 hours before 11'o clock p.m is 8 p.m.


1 Answers

You need to consider what you mean by 'time'. There are two concepts, time points and durations. It doesn't make any sense to add time points together. It does make sense to add and subtract durations (resulting in a duration), and it makes sense to add and subtract a duration with a time point (resulting in a new time point offset from the original). It also makes sense to subtract one time point from another, producing the intervening duration.

Many time APIs don't do a great job differentiating between the two concepts, but the standard C++ <chrono> library does.

Here's some code that abuses the C tm type in order to get a couple durations from the user, adds them together, and then abuses tm again to output the result.

#include <iostream> // cout, cin
#include <iomanip>  // get_time, put_time
#include <chrono>   // hours, minutes, duration_cast

int main() {
    // input, get a couple durations to do arithmetic on
    // technically std::tm represents a time point and get_time is supposed to
    // parse a time point, but we treat the results as a duration
    std::tm t;
    std::cin >> std::get_time(&t, "%H:%M");

    auto duration1 = std::chrono::hours(t.tm_hour) + std::chrono::minutes(t.tm_min);

    std::cin >> std::get_time(&t, "%H:%M");
    auto duration2 = std::chrono::hours(t.tm_hour) + std::chrono::minutes(t.tm_min);

    // do the arithmetic
    auto sum = duration1 + duration2;

    // output
    auto hours   = std::chrono::duration_cast<std::chrono::hours>(sum);
    auto minutes = std::chrono::duration_cast<std::chrono::minutes>(sum - hours);

    t.tm_hour = hours.count();
    t.tm_min  = minutes.count();

    std::cout << std::put_time(&t, "%H:%M") << '\n';
}
like image 132
bames53 Avatar answered Oct 01 '22 00:10

bames53