21

目前我使用这个代码

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

4

6 回答 6

25

不要在 Boost 上浪费时间(我知道很多人会被这种说法冒犯并认为它是异端邪说)。

该讨论包含两个非常可行的解决方案,它们不需要您将自己束缚于非标准的 3rd 方库。

C++ 在 Linux 上获取毫秒时间——clock() 似乎不能正常工作

http://linux.die.net/man/3/clock_gettime

可以在 opengroup.org 上找到对 gettimeofday 的引用

于 2013-04-18T12:02:12.510 回答
18

您可以使用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()(或者sprintf()_s如果您对非可移植的仅 VC++ 代码感兴趣)将这些字段格式化为原始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';    
}

///////////////////////////////////////////////////////////////////////////////
于 2013-04-18T09:46:35.333 回答
14

这是我在不使用 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);
}
于 2018-06-19T08:26:49.890 回答
6

您可以使用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();
}
于 2013-04-18T08:06:40.337 回答
5

这是一个非常古老的问题,但对于其他访问的人来说,这是我使用现代 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 (&current_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 (&current_localtime, "%T") << "." << std::setw (3) << std::setfill ('0') << current_milliseconds;
    return stream.str();
}
于 2021-02-20T12:29:30.807 回答
3

我建议使用 Boost.Chrono 而不是 Boost.Datetime 库,因为 Chrono 已成为 C++11 的一部分。这里的例子

于 2013-04-18T12:18:05.350 回答