日期时间到 UTC

DateTime to UTC

将日期时间值转换为以毫秒为单位的 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 ???;
}

假设您指的是自 "the 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 } });
}