With the recent edit that the input string represents a UTC date/time, the problem becomes both simpler and more complex.
- Simpler in that there are no complications with time zones and daylight saving and politicians.
- More complex in that there is no portable C or C++ solution (prior to C++20), though there are platform-dependent solutions.
This answer proposes a portable solution that is new in C++20. However if you don't have C++20, there exists a free, open-source, header-only solution that previews this part of C++20 which works with C++11/14/17 and on all platforms.
#include <chrono>
#include <fmt>
#include <iostream>
#include <sstream>
std::string
test(std::string ts)
{
using namespace std::chrono;
std::istringstream in{std::move(ts)};
sys_seconds tp;
in >> parse("%F %H:%M", tp);
return std::format("{:%F %H:%M}", tp + 2h);
}
int
main()
{
std::cout << test("2021-11-15 12:10") << '\n';
}
The above is the C++20 solution. The type sys_seconds
is a Unix timestamp. It counts seconds since 1970-01-01 00:00:00 UTC, excluding leap seconds. If you want the number of seconds out of it, that is tp.time_since_epoch().count()
.
One simply parses that, adds two hours to it, and formats it. The local time zone is never considered, and so there are no corner cases. This simply always works.
For example if the local time zone is "America/New_York", and the input string is "2021-11-07 00:10", then the output string is "2021-11-07 02:10". However if this input string is used with the currently accepted answer, then the output string is an hour less: "2021-11-07 01:10".
To use the free, open-source, header-only solution:
- Replace
#include <fmt>
with #include "date/date.h"
- Add
using namespace date;
- Change the last line to
return format("%F %H:%M", tp + 2h);