You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中获取含毫秒的UTC时间?

解决Boost获取带毫秒的UTC时间问题

问题出在你当前的代码只获取了日期部分,没有包含带毫秒的时间信息,而且使用的工具类也只针对日期格式化,咱们一步步来修正:

1. 核心问题分析

  • bg::day_clock::universal_day() 返回的是 boost::gregorian::date 类型,仅包含年/月/日,没有时分秒和毫秒,所以输出的时间部分默认是 00:00:00
  • bg::date_facet 是专门用来格式化日期的 facet,无法处理时间的毫秒部分

2. 修正方案代码

要获取带毫秒的UTC时间,需要用到Boost.DateTime的posix_time模块,它支持包含毫秒的时间戳。以下是修正后的完整代码:

#include <string>
#include <sstream>
#include <boost/date_time/posix_time/posix_time.hpp>

std::string getCurrentUTC() {
    namespace pt = boost::posix_time;
    
    // 获取带微秒的当前UTC时间(可以精确到毫秒)
    pt::ptime now = pt::microsec_clock::universal_time();
    
    // 定义格式化字符串,%f表示小数部分(默认是微秒,我们后续调整为3位毫秒)
    static char const* const fmt = "%Y-%b-%d %H:%M:%S.%f";
    
    std::ostringstream ss;
    // 创建时间格式化facet,设置只保留3位毫秒
    pt::time_facet* facet = new pt::time_facet(fmt);
    facet->fractional_digits(3);
    
    ss.imbue(std::locale(std::cout.getloc(), facet));
    ss << now;
    
    return ss.str();
}

3. 代码说明

  • pt::microsec_clock::universal_time():获取当前UTC时间,精确到微秒,返回的ptime对象包含完整的日期和时间信息
  • pt::time_facet:专门用于格式化ptime类型的工具,替代原来的date_facet
  • facet->fractional_digits(3):将小数部分从默认的6位微秒截断为3位毫秒,这样输出的就是.000格式的毫秒部分
  • 格式化字符串%Y-%b-%d %H:%M:%S.%f:其中%f对应时间的小数部分,配合fractional_digits(3)就会输出三位毫秒

4. 测试输出

调用这个函数后,你会得到类似这样的结果:

2020-Jun-29 12:34:56.789

内容的提问来源于stack exchange,提问作者QuickDzen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:02:45