How to add N hours to a date string in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
#include <chrono>
#include <format>
#include <string>

std::string addHoursModern(const std::string& dateStr, int hoursToAdd) {
    std::istringstream ss(dateStr);
    std::chrono::local_seconds tp;
    std::string tz;
    
    // 1. Parse the main date components directly into a local time point
    ss >> std::chrono::parse("%b %d %Y %I:%M %p", tp);
    ss >> tz; // Captures trailing timezone word ("EST")
    
    if (ss.fail()) {
        return "Error: Parsing failed.";
    }
    
    // 2. Add hours using type-safe chrono durations
    tp += std::chrono::hours(hoursToAdd);
    
    // 3. Reformat back to string using std::format
    return std::format("{:%b %d %Y %I:%M %p} ", tp) + tz;
}

int main() {
    std::string s = "May 21 2026 7:30 pm EST";
    
    std::cout << "Original: " << s << "\n";
    std::cout << "+5 Hours: " << addHoursModern(s, 5) << "\n";
}



/*
run:

Original: May 21 2026 7:30 pm EST
+5 Hours: May 22 2026 12:30 AM EST

*/

 



answered May 21 by avibootz

Related questions

3 answers 258 views
1 answer 128 views
128 views asked Mar 24, 2022 by avibootz
1 answer 201 views
1 answer 193 views
1 answer 135 views
135 views asked Mar 21, 2022 by avibootz
1 answer 110 views
...