How to get the current date and time in New York with C++

1 Answer

0 votes
#include <iostream>
#include <chrono>
#include <iomanip> // put_time

int main() {
    // Get current time as time_t
    auto now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);

    // Convert to tm structure for local time in New York
    std::tm* new_york_time = std::gmtime(&now_c);
    new_york_time->tm_hour -= 5; // Adjust for New York time zone (UTC-5)

    // Handle potential day change due to time zone adjustment
    std::mktime(new_york_time);

    std::cout << "Current date and time in New York: "
              << std::put_time(new_york_time, "%Y-%m-%d %H:%M:%S") << std::endl;
}


/*
run:

Current date and time in New York: 2025-02-27 02:15:13

*/

 



answered Feb 27, 2025 by avibootz

Related questions

1 answer 140 views
1 answer 164 views
1 answer 163 views
1 answer 88 views
1 answer 136 views
1 answer 147 views
...