加速,以分钟为单位获得UTC时间

时间:2020-06-29 15:12:30

标签: c++ c++11 boost

我希望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)中删除秒部分。 我该怎么做...?

预先感谢...

3 个答案:

答案 0 :(得分:3)

您可以使用自定义构面,只需从以下格式中删除“ seconds”标志(%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

答案 1 :(得分: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;

答案 2 :(得分:1)

仅删除字符串的后3个字符怎么办?

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