Home > Enterprise >  Compare DayTime strings in C
Compare DayTime strings in C

Time:07-09

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.

  1. 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 that date::from_stream parses the date and time input string into a time point (tp1) correctly.
  2. Get the date two days ahead of tp1, that is, tp1 days{2}.
  3. Format the new date back to a string by using date::format.

[Demo]

#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
  • Related