tgbotxx 1.2.9.5
Telegram Bot C++ Library
Loading...
Searching...
No Matches
DateTimeUtils.hpp
Go to the documentation of this file.
1#pragma once
2#include <ctime>
3#include <iomanip>
4#include <sstream>
5#include <string>
6
7namespace tgbotxx {
9 namespace DateTimeUtils {
15 [[nodiscard]] static std::string toString(const std::time_t& time, const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
16 std::tm tm_{};
17
18#ifdef _WIN32
20#else
22#endif
23
24 std::string result(128, '\0');
25 const std::size_t size = std::strftime(result.data(), result.size(), format.data(), &tm_);
26 if (size == 0) return {};
27
28 result.resize(size);
29 return result;
30 }
31
36 [[nodiscard]] static std::time_t fromString(const std::string& dateTimeStr, const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
37 std::tm tm{};
38 std::istringstream iss{dateTimeStr};
39
40 if (!(iss >> std::get_time(&tm, format.data()))) {
41 return -1; // failed to parse dateTimeStr
42 }
43
44 tm.tm_isdst = -1;
45 return std::mktime(&tm);
46 }
47
51 [[nodiscard]] static std::string now(const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
52 const std::time_t tm = std::time(nullptr);
53 return toString(tm, format);
54 }
55
56 [[deprecated("Use DateTimeUtils::now() instead")]] [[nodiscard]] static std::string currentDateTime(const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
57 return now(format);
58 }
59
60 }
61}
static std::string now(const std::string_view &format="%Y-%m-%d %H:%M:%S")
returns current date and time as a string with a specific format
static std::string toString(const std::time_t &time, const std::string_view &format="%Y-%m-%d %H:%M:%S")
Converts an std::time_t to a string date time with a specific format.
static std::string currentDateTime(const std::string_view &format="%Y-%m-%d %H:%M:%S")
static std::time_t fromString(const std::string &dateTimeStr, const std::string_view &format="%Y-%m-%d %H:%M:%S")
Converts a string date time with a specific format to an std::time_t.
std::shared_ptr< T > Ptr
Definition Ptr.hpp:6