mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-03-28 16:36:04 +01:00
util: Implement ParseISO8601DateTime based on C++20
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2022 The Bitcoin Core developers
|
||||
// Copyright (c) 2009-present The Bitcoin Core developers
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
@@ -8,10 +8,13 @@
|
||||
#include <compat/compat.h>
|
||||
#include <tinyformat.h>
|
||||
#include <util/check.h>
|
||||
#include <util/strencodings.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
|
||||
void UninterruptibleSleep(const std::chrono::microseconds& n) { std::this_thread::sleep_for(n); }
|
||||
@@ -60,6 +63,30 @@ std::string FormatISO8601Date(int64_t nTime)
|
||||
return strprintf("%04i-%02u-%02u", signed{ymd.year()}, unsigned{ymd.month()}, unsigned{ymd.day()});
|
||||
}
|
||||
|
||||
std::optional<int64_t> ParseISO8601DateTime(std::string_view str)
|
||||
{
|
||||
constexpr auto FMT_SIZE{std::string_view{"2000-01-01T01:01:01Z"}.size()};
|
||||
if (str.size() != FMT_SIZE || str[4] != '-' || str[7] != '-' || str[10] != 'T' || str[13] != ':' || str[16] != ':' || str[19] != 'Z') {
|
||||
return {};
|
||||
}
|
||||
const auto year{ToIntegral<uint16_t>(str.substr(0, 4))};
|
||||
const auto month{ToIntegral<uint8_t>(str.substr(5, 2))};
|
||||
const auto day{ToIntegral<uint8_t>(str.substr(8, 2))};
|
||||
const auto hour{ToIntegral<uint8_t>(str.substr(11, 2))};
|
||||
const auto min{ToIntegral<uint8_t>(str.substr(14, 2))};
|
||||
const auto sec{ToIntegral<uint8_t>(str.substr(17, 2))};
|
||||
if (!year || !month || !day || !hour || !min || !sec) {
|
||||
return {};
|
||||
}
|
||||
const std::chrono::year_month_day ymd{std::chrono::year{*year}, std::chrono::month{*month}, std::chrono::day{*day}};
|
||||
if (!ymd.ok()) {
|
||||
return {};
|
||||
}
|
||||
const auto time{std::chrono::hours{*hour} + std::chrono::minutes{*min} + std::chrono::seconds{*sec}};
|
||||
const auto tp{std::chrono::sys_days{ymd} + time};
|
||||
return int64_t{TicksSinceEpoch<std::chrono::seconds>(tp)};
|
||||
}
|
||||
|
||||
struct timeval MillisToTimeval(int64_t nTimeout)
|
||||
{
|
||||
struct timeval timeout;
|
||||
|
||||
Reference in New Issue
Block a user