【问题标题】:Boost, get UTC time in minutes precision提升,以分钟精度获得 UTC 时间
【发布时间】:2020-10-19 19:07:42
【问题描述】:

我想要以分钟为单位的 UTC 时间,我不想要秒。我在做……

auto timeUTC = boost::posix_time::second_clock::universal_time();
std::cout << to_iso_extended_string(timeUTC) << std::endl;

这会将时间打印为2020-06-29T23:06:30

我希望从ptime 对象中删除秒部分,例如2020-06-29T23:06:00。 我该怎么做...?

提前谢谢...

【问题讨论】:

    标签: c++ c++11 boost


    【解决方案1】:

    您可以使用自定义方面,只需从格式中删除“秒”标志 (%S):

    #include <iostream>
    #include "boost/date_time/posix_time/posix_time.hpp"
    
    using boost::posix_time::time_facet;
    int main()
    {
        auto timeUTC = boost::posix_time::second_clock::universal_time();
        std::cout << "iso extended string: \n\t";
        std::cout << to_iso_extended_string(timeUTC) << std::endl;
        
        std::cout << "custom facet: \n\t";
        time_facet* custom_facet = new time_facet("%Y-%m-%dT%H:%M");
        std::cout.imbue(std::locale(std::locale::classic(), custom_facet)); 
        std::cout << timeUTC << std::endl;
    }
    

    Live Demo

    输出:

    iso extended string: 
        2020-06-29T19:40:30
    custom facet: 
        2020-06-29T19:40
    

    您也可以使用此构面来简单地为秒写零:

    time_facet* custom_facet = new time_facet("%Y-%m-%dT%H:%M:00");
    

    如果您希望实际更改内部表示以使秒数为零,则可以转换为tm

    auto as_tm = to_tm(timeUTC);
    as_tm.tm_sec = 0;
    auto zeroed_seconds = boost::posix_time::ptime_from_tm(as_tm);
    

    Live Demo 2

    【讨论】:

      【解决方案2】:

      这将创建一个秒数归零的 ptime:

      auto ptimeUtc = boost::posix_time::second_clock::universal_time();
      auto date = ptimeUtc.date();
      auto time = ptimeUtc.time_of_day();
      auto timeRounded = pt::time_duration(time.hours(), time.minutes(), 0);
      pt::ptime ptimeUtcRounded(date, timeRounded);
      std::cout << to_iso_extended_string(ptimeUtcRounded) << std::endl;
      

      【讨论】:

        【解决方案3】:

        只删除字符串的最后 3 个字符怎么样?

        auto timeUTCString = to_iso_extended_string(timeUTC);
        std::cout << timeUTCString.substr(0, timeUTCString.length() - 3) << std::endl;
        

        【讨论】:

        • 我想要 ptime 对象中的归零数据。
        • 我看到了。 @AndyG 的答案是要走的路。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多