将秒转换为小时、分钟、秒.百分之一秒

Convert seconds to hours, minutes, seconds.hundreths of a second

本文关键字:分钟 百分之一 转换 小时      更新时间:2023-10-16

我有一个包含秒数的双精度值,可能是负数,我想要一个格式为 H:mm:ss.hhh 或 -H:mm:ss.hhh 的字符串

std::string getFormattedTime(double seconds)
{
// magic voodoo
}

如果小时为零,我将需要省略小时。

我已经两次遇到各种舍入和精度问题,所以我认为是时候寻求帮助了:)

std::string getLabelForPosition(double seconds)
{
bool negative = seconds < 0.0;
if (negative)
seconds *= -1.0;
double mins = std::floor(std::round(seconds) / 60.0);
double secs = seconds - mins * 60.0;
std::stringstream s; 
if (negative)
s << "-";
s << mins << ":" << std::fixed << std::setprecision(decimalPlaces) << secs; 

return s.str();
}

让我知道这是否适合您。我敢打赌有一种更简单的方法。

std::string getFormattedTime(double seconds)
{
double s(fabs(seconds));
int h(s/3600);
int min(s/60 - h*60);
double sec(s - (h*60 + min)*60);
std::ostringstream oss;
oss<<std::setfill('0')<<std::setw(2)<<fabs(seconds)/seconds*h<<":"<<std::setw(2)<<min<<":";
if (sec/10<1)
oss<<"0";
oss<<sec;
return oss.str().c_str();
}

这是一个使用boost的解决方案。 假设您有boost::uint64_t secondsSinceEpoch表示自纪元以来的秒数(我个人不明白您在这种情况下使用双精度的想法,抱歉(。 然后要获得字符串表示形式,只需使用boost::posix_time::to_simple_string(secondsSinceEpoch);

std::string getLabelForPosition(double doubleSeconds)
{
int64 msInt = int64(std::round(doubleSeconds * 1000.0));
int64 absInt = std::abs(msInt);
std::stringstream s; 
if (msInt < 0)
s << "-";
auto hours = absInt / (1000 * 60 * 60);
auto minutes = absInt / (1000 * 60) % 60;
auto secondsx = absInt / 1000 % 60;
auto milliseconds = absInt % 1000;

if (hours > 0)
s << std::setfill('0')
<< hours
<< "::";
s << minutes
<< std::setfill('0')
<< ":"
<< std::setw(2)
<< secondsx
<< "."
<< std::setw(3)
<< milliseconds;
return s.str();
}

这几乎是正确的。 实际实现使用缓存来避免在屏幕重新呈现时重新执行所有操作。