tgbotxx 1.1.9.2
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 {
14 [[nodiscard]] static std::string toString(const std::time_t& time, const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
15 char buffer[128]{};
16 tm tm_{};
17#ifdef _WIN32
18 localtime_s(&tm_, &time);
19#else
20 tm_ = *std::localtime(&time);
21#endif
22 std::strftime(buffer, sizeof(buffer), format.data(), &tm_);
23 return std::string{buffer};
24 }
25
30 [[nodiscard]] static std::time_t fromString(const std::string& dateTimeStr, const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
31 std::tm tm{};
32 std::istringstream iss{dateTimeStr};
33 iss >> std::get_time(&tm, format.data());
34 tm.tm_isdst = -1; // let mktime() determine DST correctly
35 return std::mktime(&tm);
36 }
37
41 [[nodiscard]] static std::string now(const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
42 const std::time_t tm = std::time(nullptr);
43 return toString(tm, format);
44 }
45
46 [[deprecated("Use DateTimeUtils::now() instead")]]
47 [[nodiscard]] static std::string currentDateTime(const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
48 return now(format);
49 }
50
51 }
52}
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.