How to format time hours-minutes-seconds in C++

2 Answers

0 votes
#include <iostream>
#include <iomanip> // For std::setw and std::setfill

int main() {
    int hours = 9, minutes = 36, seconds = 7;

    // Format and print time as HH:MM:SS
    std::cout << std::setw(2) << std::setfill('0') << hours << ":"
              << std::setw(2) << std::setfill('0') << minutes << ":"
              << std::setw(2) << std::setfill('0') << seconds << std::endl;
}



/*
run:

09:36:07

*/

 



answered Jul 22, 2025 by avibootz
0 votes
#include <iostream>
#include <iomanip>
#include <ctime>

int main() {
    // Create a tm struct with the desired date and time
    std::tm date = {};
    date.tm_year = 2024 - 1900; // Years since 1900
    date.tm_mon  = 12 - 1;      // Months since January
    date.tm_mday = 10;
    date.tm_hour = 15;
    date.tm_min  = 21;
    date.tm_sec  = 42;

    // Format the time as HH:mm:ss
    std::cout << std::put_time(&date, "%H:%M:%S") << std::endl;
}




/*
run:

15:21:42

*/

 



answered Jul 22, 2025 by avibootz

Related questions

1 answer 90 views
1 answer 89 views
1 answer 94 views
1 answer 87 views
1 answer 95 views
1 answer 104 views
1 answer 114 views
...