tgbotxx  1.1.6.9
Telegram Bot C++ Library
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 
7 namespace 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  return std::mktime(&tm);
35  }
36 
40  [[nodiscard]] static std::string now(const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
41  const std::time_t tm = std::time(nullptr);
42  return toString(tm, format);
43  }
44 
45  [[deprecated("Use DateTimeUtils::now() instead")]]
46  [[nodiscard]] static std::string currentDateTime(const std::string_view& format = "%Y-%m-%d %H:%M:%S") {
47  return now(format);
48  }
49 
50  }
51 }
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.
Definition: Api.hpp:14