你可以使用
Boost’s Posix Time。
您可以使用boost :: posix_time :: microsec_clock :: local_time()获取当前时间从微秒分辨率时钟:
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
然后,您可以计算当前日期的时间偏移量(因为您的持续时间输出格式为< hours>:< minutes>:< seconds>。< milliseconds>,我假定它们是当前日偏移量;如果没有,请随时在持续时间/时间间隔内使用另一个起点):
boost::posix_time::time_duration td = now.time_of_day();
然后可以使用.hours(),.minutes(),.seconds()访问器来获取相应的值。
不幸的是,似乎没有.milliseconds()访问器,但是有一个.total_milliseconds()一个;所以你可以做一些减法数学,以获得在字符串中格式化剩余的毫秒数。
那么你可以使用sprintf()(或者sprintf()_ s,如果你对非便携式VC – 唯一代码感兴趣)将这些字段格式化成一个原始的char缓冲区,并将这个原始的C字符串缓冲区安全地包装到一个强大的方便的std中: :字符串实例。
有关详细信息,请参阅下面的注释代码。
控制台中的输出类似于:
11:43:52.276
示例代码:
///
#include // for sprintf()
#include // for console output
#include // for std::string
#include
//-----------------------------------------------------------------------------
// Format current time (calculated as an offset in current day) in this form:
//
// "hh:mm:ss.SSS" (where "SSS" are milliseconds)
//-----------------------------------------------------------------------------
std::string now_str()
{
// Get current time from the clock, using microseconds resolution
const boost::posix_time::ptime now =
boost::posix_time::microsec_clock::local_time();
// Get the time offset in current day
const boost::posix_time::time_duration td = now.time_of_day();
//
// Extract hours, minutes, seconds and milliseconds.
//
// Since there is no direct accessor ".milliseconds()",
// milliseconds are computed _by difference_ between total milliseconds
// (for which there is an accessor), and the hours/minutes/seconds
// values previously fetched.
//
const long hours = td.hours();
const long minutes = td.minutes();
const long seconds = td.seconds();
const long milliseconds = td.total_milliseconds() -
((hours * 3600 + minutes * 60 + seconds) * 1000);
//
// Format like this:
//
// hh:mm:ss.SSS
//
// e.g. 02:15:40:321
//
// ^ ^
// | |
// 123456789*12
// ---------10- --> 12 chars + \0 --> 13 chars should suffice
//
//
char buf[40];
sprintf(buf, "%02ld:%02ld:%02ld.%03ld",
hours, minutes, seconds, milliseconds);
return buf;
}
int main()
{
std::cout << now_str() << '\n';
}
///