2020-07-05 08:01:30 +02:00
|
|
|
/* This file is part of FediBlock-backend.
|
|
|
|
* Copyright © 2020 tastytea <tastytea@tastytea.de>
|
|
|
|
*
|
|
|
|
* This program is free software: you can redistribute it and/or modify
|
|
|
|
* it under the terms of the GNU Affero General Public License as published by
|
|
|
|
* the Free Software Foundation, version 3.
|
|
|
|
*
|
|
|
|
* This program is distributed in the hope that it will be useful,
|
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
* GNU Affero General Public License for more details.
|
|
|
|
*
|
|
|
|
* You should have received a copy of the GNU Affero General Public License
|
|
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "time.hpp"
|
|
|
|
|
2020-07-05 11:38:11 +02:00
|
|
|
#include <chrono>
|
2020-07-05 08:01:30 +02:00
|
|
|
#include <cstdint>
|
|
|
|
#include <ctime>
|
2020-07-05 11:38:11 +02:00
|
|
|
#include <iomanip>
|
|
|
|
#include <sstream>
|
|
|
|
#include <string>
|
2020-07-05 08:01:30 +02:00
|
|
|
#include <string_view>
|
|
|
|
|
|
|
|
namespace FediBlock::time
|
|
|
|
{
|
|
|
|
|
2020-07-05 11:38:11 +02:00
|
|
|
using std::get_time;
|
|
|
|
using std::strftime;
|
|
|
|
using std::string;
|
2020-07-05 08:01:30 +02:00
|
|
|
using std::string_view;
|
2020-07-05 11:38:11 +02:00
|
|
|
using std::stringstream;
|
2020-07-05 08:01:30 +02:00
|
|
|
using std::time_t;
|
|
|
|
using std::uint16_t;
|
2020-07-05 11:38:11 +02:00
|
|
|
using std::chrono::system_clock;
|
2020-07-05 08:01:30 +02:00
|
|
|
|
|
|
|
string to_string(const system_clock::time_point &timepoint,
|
|
|
|
const string_view format)
|
|
|
|
{
|
|
|
|
constexpr uint16_t bufsize = 1024;
|
|
|
|
time_t time = system_clock::to_time_t(timepoint);
|
|
|
|
std::tm *tm{nullptr};
|
|
|
|
tm = std::gmtime(&time);
|
|
|
|
char buffer[bufsize];
|
2020-07-05 11:38:11 +02:00
|
|
|
strftime(buffer, bufsize, format.data(), tm);
|
2020-07-05 08:01:30 +02:00
|
|
|
|
|
|
|
return buffer;
|
|
|
|
}
|
|
|
|
|
2020-07-05 11:38:11 +02:00
|
|
|
string to_string(const string_view timestring, const string_view format)
|
|
|
|
{
|
|
|
|
std::tm tm{};
|
|
|
|
tm.tm_isdst = -1; // Detect daylight saving time.
|
|
|
|
stringstream ss(timestring.data());
|
2020-10-28 10:52:16 +01:00
|
|
|
ss >> get_time(&tm, "%Y-%m-%dT%T"); // Assume time is UTC (%F doesn't work).
|
2020-07-05 11:38:11 +02:00
|
|
|
|
|
|
|
return to_string(system_clock::from_time_t(timegm(&tm)), format);
|
|
|
|
}
|
|
|
|
|
2020-07-05 08:01:30 +02:00
|
|
|
} // namespace FediBlock::time
|