C ++将字符串时间戳转换为std :: chrono :: system_clock :: time_point

时间:2018-02-16 12:55:27

标签: c++ time timestamp boost-date-time

我正在尝试转换以下列格式表示的字符串时间戳:" 28.08.2017 03:59:55.0007"通过保留微秒精度到std :: chrono :: system_clock :: time_point。 有没有办法通过使用标准库或提升来实现这一目标? 感谢。

3 个答案:

答案 0 :(得分:3)

我会使用Howard Hinnant的日期库https://howardhinnant.github.io/date/date.html

e.g:

std::stringstream str( "28.08.2017 03:59:55.0007" );
str.imbue( std::locale() );
std::chrono::time_point< std::chrono::system_clock, std::chrono::microseconds > result;
date::from_stream( str, "%d.%m.%Y %H:%M:%S", result );
std::cout << result.time_since_epoch().count();

答案 1 :(得分:1)

一个实现可以是:

#include <ctime>
#include <cmath>
#include <chrono>
#include <string>
#include <cstdint>
#include <stdexcept>

std::chrono::system_clock::time_point parse_my_timestamp(std::string const& timestamp) {
    auto error = [&timestamp]() { throw std::invalid_argument("Invalid timestamp: "  + timestamp); };
    std::tm tm;
    auto fraction = ::strptime(timestamp.c_str(), "%d.%m.%Y %H:%M:%S", &tm);
    if(!fraction)
        error();
    std::chrono::nanoseconds ns(0);
    if('.' == *fraction) {
        ++fraction;
        char* fraction_end = 0;
        std::chrono::nanoseconds fraction_value(std::strtoul(fraction, &fraction_end, 10));
        if(fraction_end != timestamp.data() + timestamp.size())
            error();
        auto fraction_len = fraction_end - fraction;
        if(fraction_len > 9)
            error();
        ns = fraction_value * static_cast<std::int32_t>(std::pow(10, 9 - fraction_len));
    }
    else if(fraction != timestamp.data() + timestamp.size())
        error();
    auto seconds_since_epoch = std::mktime(&tm); // Assumes timestamp is in localtime. For UTC use timegm.
    auto timepoint_ns = std::chrono::system_clock::from_time_t(seconds_since_epoch) + ns;
    return std::chrono::time_point_cast<std::chrono::system_clock::duration>(timepoint_ns);
}

答案 2 :(得分:1)

我想添加一个答案,因为没有专门使用该标准的答案。
根据输入:istringstream timestamp("28.08.2017 03:59:55.0007"),可以通过get_time将其转换为tm,但是小数秒。小数秒需要手动转换(这可以通过从舍入余数除以chrono::microseconds比率构建micro来完成。)所有这些都可以组合成这样的:

tm tmb;
double r;

timestamp >> get_time(&tmb, "%d.%m.%Y %T") >> r;

const auto output = chrono::time_point_cast<chrono::microseconds>(chrono::system_clock::from_time_t(mktime(&tmb))) + chrono::microseconds(lround(r * micro::den));

Live Example