如何将秒转换为 hh:mm:ss.millisecond 格式 C++?

Tan*_*zar 2 c++ time c++11

我需要将秒转换为 hh:mm:ss.milliseconds 并且我需要必须遵守此格式。我的意思是小时、分钟和秒必须有 2 位数字,而毫秒必须有 3 位数字。例如,如果秒 = 3907.1 我会获得 01:05:07.100

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sstream>
#include <math.h>
using namespace std;

int main()
{   
    double sec_tot = 3907.1;
    double hour = sec_tot/3600; // seconds in hours
    double hour_int;
    double hour_fra = modf(hour, &hour_int );//split integer and decimal part of hours
    double minutes = hour_fra*60; // dacimal hours in minutes
    double minutes_int;
    double minutes_fra = modf(minutes, &minutes_int); // split integer and decimal part of minutes
    double seconds = minutes_fra*60; // decimal minutes in seconds
    stringstream ss;
    ss << ("%02lf", hour_int) << ":" << ("%02lf", minutes_int) << ":" << ("%02lf", seconds);
    string time_obs_def = ss.str();
    cout << time_obs_def << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但输出是 1:5:7.1 谢谢。

Ted*_*gmo 6

现在你可能应该使用 chrono 持续时间std::chrono::milliseconds来完成这样的任务,但是如果你想创建我们自己的类型来支持格式化,那么应该这样做:

#include <iomanip>   // std::setw & std::setfill
#include <iostream>

// your own type
struct seconds_t {
    double value;
};

// ostream operator for your type:
std::ostream& operator<<(std::ostream& os, const seconds_t& v) {
    // convert to milliseconds
    int ms = static_cast<int>(v.value * 1000.);

    int h = ms / (1000 * 60 * 60);
    ms -= h * (1000 * 60 * 60);

    int m = ms / (1000 * 60);
    ms -= m * (1000 * 60);

    int s = ms / 1000;
    ms -= s * 1000;

    return os << std::setfill('0') << std::setw(2) << h << ':' << std::setw(2) << m
              << ':' << std::setw(2) << s << '.' << std::setw(3) << ms;
}

int main() {
    seconds_t m{3907.1};
    std::cout << m << "\n";
}
Run Code Online (Sandbox Code Playgroud)