如何用c语言打印系统时间,如何使用C/C打印当前时间(毫秒)11

你可以使用

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';

}

///

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值