Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix parsing iso date in date tests #168

Merged
merged 7 commits into from
Oct 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/modules/date/Date.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "faker-cxx/Date.h"

#include <chrono>
#include <ctime>

#include "data/MonthNames.h"
#include "data/WeekdayNames.h"
Expand Down
42 changes: 11 additions & 31 deletions src/modules/date/DateTest.cpp
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
#include "faker-cxx/Date.h"

#include <algorithm>
#include <charconv>
#include <chrono>

#include "gtest/gtest.h"

#include "../../common/StringHelper.h"
#include "data/MonthNames.h"
#include "data/WeekdayNames.h"

#ifdef _WIN32
#define timegm _mkgmtime
#endif

using namespace ::testing;
using namespace faker;

Expand All @@ -28,39 +30,17 @@ class DateTest : public Test
{
auto dateTime = parseISOFormattedStringToTm(isoString);

return std::chrono::system_clock::from_time_t(mktime(&dateTime));
return std::chrono::system_clock::from_time_t(timegm(&dateTime));
}

static tm parseISOFormattedStringToTm(const std::string& isoString)
{
const auto isoStringDateTime = StringHelper::split(isoString, "T");

const auto& date = isoStringDateTime[0];
const auto dateElements = StringHelper::split(date, "-");
int year, month, day;
std::from_chars(dateElements[0].data(), dateElements[0].data() + dateElements[0].size(), year);
std::from_chars(dateElements[1].data(), dateElements[1].data() + dateElements[1].size(), month);
std::from_chars(dateElements[2].data(), dateElements[2].data() + dateElements[2].size(), day);

const auto& time = isoStringDateTime[1];
const auto timeElements = StringHelper::split(time, ":");

int hour, minutes, seconds;
std::from_chars(timeElements[0].data(), timeElements[0].data() + timeElements[0].size(), hour);
std::from_chars(timeElements[1].data(), timeElements[1].data() + timeElements[1].size(), minutes);
std::from_chars(timeElements[2].data(), timeElements[2].data() + timeElements[2].size(), seconds);

tm dateTime{};

dateTime.tm_year = year - 1900;
dateTime.tm_mon = month - 1;
dateTime.tm_mday = day;
dateTime.tm_hour = hour;
dateTime.tm_min = minutes;
dateTime.tm_sec = seconds;
dateTime.tm_isdst = -1;

return dateTime;
tm tm{};

std::istringstream iss(isoString);
iss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%SZ");

return tm;
}
};

Expand Down