If I have a single string storing both Day and Time in the format "mm/dd-hh:mm" how can I create the string of two days ahead?
CodePudding user response:
You can use Howard Hinnant's date library.
- First of all, fix the input string by adding something that could be parsed as a year, and not a leap year (e.g.
"01/"
), so thatdate::from_stream
parses the date and time input string into a time point (tp1
) correctly. - Get the date two days ahead of
tp1
, that is,tp1 days{2}
. - Format the new date back to a string by using
date::format
.
#include <chrono>
#include <date/date.h>
#include <iostream> // cout
#include <sstream> // istringstream
#include <string>
std::string two_days_ahead(const std::string& dt) {
auto fixed_dt{std::string{"01/"} dt};
std::istringstream iss{fixed_dt};
date::sys_time<std::chrono::minutes> tp1{};
date::from_stream(iss, "%y/%m/%d-%H:%M", tp1);
return date::format("%m/%d-%H:%M", tp1 date::days{2});
}
int main() {
std::cout << two_days_ahead("10/30-09:50") << "\n";
}
// Input: "10/30-09:50"
// Output: 11/01-09:50