Added daylight savings time detection to Easy::Entity::get_time().

This commit is contained in:
tastytea 2019-04-18 04:46:55 +02:00
parent 5dee115f8f
commit 7f46be68d1
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
2 changed files with 8 additions and 7 deletions

View File

@ -14,10 +14,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <ctime>
#include <iomanip> // get_time #include <iomanip> // get_time
#include <sstream> #include <sstream>
#include <chrono> #include <chrono>
#include <ctime>
#include <regex> #include <regex>
#include <algorithm> #include <algorithm>
#include "easy/entity.hpp" #include "easy/entity.hpp"
@ -233,9 +233,10 @@ const Easy::time Easy::Entity::get_time(const string &key) const
if (node.isString()) if (node.isString())
{ {
std::stringstream sstime(node.asString()); std::stringstream sstime(node.asString());
struct std::tm tm; struct std::tm tm = {};
tm.tm_isdst = -1; // Detect daylight saving time.
sstime >> std::get_time(&tm, "%Y-%m-%dT%T"); sstime >> std::get_time(&tm, "%Y-%m-%dT%T");
std::time_t time = timegm(&tm); std::time_t time = timegm(&tm); // Assume time is UTC.
_was_set = true; _was_set = true;
return { system_clock::from_time_t(time) }; return { system_clock::from_time_t(time) };
} }

View File

@ -32,18 +32,18 @@ const string Easy::time::strtime(const string &format, const bool &local) const
{ {
constexpr std::uint16_t bufsize = 1024; constexpr std::uint16_t bufsize = 1024;
std::time_t time = system_clock::to_time_t(timepoint); std::time_t time = system_clock::to_time_t(timepoint);
std::tm *timeinfo; std::tm *tm;
if (local) if (local)
{ {
timeinfo = std::localtime(&time); tm = std::localtime(&time);
} }
else else
{ {
timeinfo = std::gmtime(&time); tm = std::gmtime(&time);
} }
char buffer[bufsize]; char buffer[bufsize];
std::strftime(buffer, bufsize, format.c_str(), timeinfo); std::strftime(buffer, bufsize, format.c_str(), tm);
return static_cast<const string>(buffer); return static_cast<const string>(buffer);
} }