如何使用C ++ / C ++ 11打印当前时间(以毫秒为单位) [英] How to print current time (with milliseconds) using C++ / C++11

查看:190
本文介绍了如何使用C ++ / C ++ 11打印当前时间(以毫秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我使用此代码

  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的Posix时间



您可以使用 boost :: posix_time :: microsec_clock :: local_time()来获取当前时间分辨率时钟:

  boost :: posix_time :: ptime now = boost :: posix_time :: microsec_clock :: local_time 

然后您可以计算当天的时间偏移(因为您的持续时间输出为< hours>:< hours>:< minutes>:< seconds>。< milliseconds> ,我假设他们是以当前日期抵消计算的;如果不是,使用另一个起始点的持续时间/时间间隔):

  boost :: posix_time :: time_duration td = now.time_of_day();然后你可以使用 .hours()。 , .minutes() .seconds()访问器获取相应的值。

不幸的是,似乎没有 .milliseconds()访问器,但是有一个 .total_milliseconds()一;所以你可以做一个减法数学得到剩余的毫秒格式化在字符串中。



然后你可以使用 sprintf code>(或 sprintf()_ s 如果您对非便携式VC ++ - 唯一代码感兴趣)将这些字段格式化为原始 char 缓冲区,并将这个原始C字符串缓冲区安全地包装到一个强大的方便的 std :: string 实例中。



有关详细信息,请参阅下面的注释代码。



在控制台中输出如下:



< blockquote>

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>


// ------------------------------------ -----------------------------------------
//格式化当前时间(以当前日的偏移量计算):
//
//hh:mm:ss.SSS(其中SSS是毫秒)
// - -------------------------------------------------- -------------------------
std :: string now_str()
{
//获取当前时间从时钟,使用微秒解决
const boost :: posix_time :: ptime now =
boost :: posix_time :: microsec_clock :: local_time();

//获取当前日期的时间偏移量
const boost :: posix_time :: time_duration td = now.time_of_day();

//
//提取小时,分钟,秒和毫秒。
//
//因为没有直接访问器.milliseconds(),
//毫秒是通过在毫秒之间的差值_
//计算的访问器)和以前读取的小时/分钟/秒
//值。
//
const long hours = td.hours();
const long minutes = td.minutes();
const long seconds = td.seconds();
const long milliseconds = td.total_milliseconds() -
((小时* 3600 +分钟* 60 +秒)* 1000);

//
//格式如下:
//
// hh:mm:ss.SSS
//
/ / eg 02:15:40:321
//
// ^ ^
// | |
// 123456789 * 12
// --------- 10- - > 12 chars + \0 - > 13个字符应该足够
//
//
char buf [40];
sprintf(buf,%02ld:%02ld:%02ld。%03ld,
小时,分钟,秒,毫秒);

return buf;
}

int main()
{
std :: cout< now_str()<< '\\\
';
}

////////////////////////////////////// ///////////////////////////////////////// b $ b


Currently I use this code

string now() {
    time_t t = time(0);
    char buffer[9] = {0};

    strftime(buffer, 9, "%H:%M:%S", localtime(&t));
    return string(buffer);
}

to format time. I need to add milliseconds, so the output has the format: 16:56:12.321

解决方案

You can use Boost's Posix Time.

You can use boost::posix_time::microsec_clock::local_time() to get current time from microseconds-resolution clock:

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

Then you can compute time offset in current day (since your duration output is in the form <hours>:<minutes>:<seconds>.<milliseconds>, I'm assuming they are calculated as current day offset; if they are not, feel free to use another starting point for duration/time interval):

boost::posix_time::time_duration td = now.time_of_day();

Then you can use .hours(), .minutes(), .seconds() accessors to get the corresponding values.
Unfortunately, there doesn't seem to be a .milliseconds() accessor, but there is a .total_milliseconds() one; so you can do a little subtraction math to get the remaining milliseconds to be formatted in the string.

Then you can use sprintf() (or sprintf()_s if you are interested in non-portable VC++-only code) to format those fields into a raw char buffer, and safely wrap this raw C string buffer into a robust convenient std::string instance.

See the commented code below for further details.

Output in console is something like:

11:43:52.276


Sample code:

///////////////////////////////////////////////////////////////////////////////

#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 ++ / C ++ 11打印当前时间(以毫秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆