DateTime到UTC

时间:2015-05-25 14:57:19

标签: c++ boost chrono

将日期时间值转换为UTC的正确方法是什么?

我一直在研究std :: chrono并且没有真正找到实现这一点的实用方法,任何想法?

auto local_time_to_utc_milliseconds(int year, int month, int day, int hour, int minute, int second, int millisecond) -> std::uint64_t
{
    return ???;
}

1 个答案:

答案 0 :(得分:1)

假设你的意思是“Epoch”(或一些众所周知的时间点)以来的毫秒数:

<强> Live On Coliru

#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

int main() {
    static const boost::posix_time::ptime epoch { { 1970, 1, 1 }, {} };

    auto now = boost::posix_time::microsec_clock::universal_time();

    std::cout << "Time in milliseconds since 1970: " << (now-epoch).total_milliseconds() << "\n";
}

打印例如

Time in milliseconds since 1970: 1432566946471

更新以符合您的签名:

auto local_time_to_utc_milliseconds(boost::posix_time::ptime& dt) -> std::uint64_t
{
    static const boost::posix_time::ptime epoch { { 1970, 1, 1 }, {} };
    return (dt - epoch).total_milliseconds();
}

auto local_time_to_utc_milliseconds(int year, int month, int day, int hour, int minute, int second, int millisecond) -> std::uint64_t
{
    return local_time_to_utc_milliseconds(boost::posix_time::ptime { { year, month, day }, { hour, minute, second, millisecond } });
}