目前我使用此代码
string now() {
time_t t = time(0);
char buffer[9] = {0};
strftime(buffer, 9, "%H:%M:%S", localtime(&t));
return string(buffer);
}
格式化时间。我需要添加毫秒,因此输出的格式为:
16:56:12.321
不要在 Boost 上浪费时间(我知道很多人会被这个说法冒犯并认为它是异端)。
本讨论包含两个非常可行的解决方案,不需要您将自己束缚于非标准的第三方库。
C++ 在 Linux 上获取毫秒时间——clock() 似乎无法正常工作
http://linux.die.net/man/3/clock_gettime
可以在 opengroup.org 找到对 gettimeofday 的参考
不使用boost的解决方案:
std::string getCurrentTimestamp()
{
using std::chrono::system_clock;
auto currentTime = std::chrono::system_clock::now();
char buffer[80];
auto transformed = currentTime.time_since_epoch().count() / 1000000;
auto millis = transformed % 1000;
std::time_t tt;
tt = system_clock::to_time_t ( currentTime );
auto timeinfo = localtime (&tt);
strftime (buffer,80,"%F %H:%M:%S",timeinfo);
sprintf(buffer, "%s:%03d",buffer,(int)millis);
return std::string(buffer);
}
您可以使用Boost的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()
(如果您对不可移植的 VC++ 代码感兴趣,则使用 sprintf()_s
)将这些字段格式化为原始 char
缓冲区,并安全地将这个原始 C 字符串缓冲区包装到一个健壮方便的std::string
实例。
有关更多详细信息,请参阅下面的注释代码。
控制台的输出类似于:
11:43:52.276
示例代码:
///////////////////////////////////////////////////////////////////////////////
#include <stdio.h> // for sprintf()
#include <iostream> // for console output
#include <string> // for std::string
#include <boost/date_time/posix_time/posix_time.hpp>
//-----------------------------------------------------------------------------
// 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';
}
///////////////////////////////////////////////////////////////////////////////
这是一个非常古老的问题,但对于其他来访的人来说,这是我使用现代 C++ 提出的解决方案......
#include <chrono>
#include <ctime>
#include <sstream>
#include <iomanip>
std::string timestamp()
{
using namespace std::chrono;
using clock = system_clock;
const auto current_time_point {clock::now()};
const auto current_time {clock::to_time_t (current_time_point)};
const auto current_localtime {*std::localtime (¤t_time)};
const auto current_time_since_epoch {current_time_point.time_since_epoch()};
const auto current_milliseconds {duration_cast<milliseconds> (current_time_since_epoch).count() % 1000};
std::ostringstream stream;
stream << std::put_time (¤t_localtime, "%T") << "." << std::setw (3) << std::setfill ('0') << current_milliseconds;
return stream.str();
}
您可以使用
boost::posix_time
。请参阅这个SO问题。例如:
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
获取当前时间:
boost::posix_time::ptime t1 = boost::posix_time::microsec_clock::local_time();
// ('tick' and 'now' are of the type of 't1')
如果您可以使用 C++11,您还可以使用 C++11 chrono。例如:
int elapsed_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
要获取当前时间(您有多个不同的时钟可用,请参阅文档):
std::chrono::time_point<std::chrono::system_clock> t2;
t2 = std::chrono::system_clock::now();
// ('start' and 'end' are of the type of 't2')
对于以毫秒为单位的时间,您可以获取午夜到当前时间之间的持续时间。 std::chrono 的示例:
unsigned int millis_since_midnight()
{
// current time
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
// get midnight
time_t tnow = std::chrono::system_clock::to_time_t(now);
tm *date = std::localtime(&tnow);
date->tm_hour = 0;
date->tm_min = 0;
date->tm_sec = 0;
auto midnight = std::chrono::system_clock::from_time_t(std::mktime(date));
// number of milliseconds between midnight and now, ie current time in millis
// The same technique can be used for time since epoch
return std::chrono::duration_cast<std::chrono::milliseconds>(now - midnight).count();
}
我建议使用 Boost.Chrono 而不是 Boost.Datetime 库,因为 Chrono 已成为 C++11 的一部分。 示例在这里