Skip to content

Commit 3687058

Browse files
authored
Fix a bug in the fromDbStringLocal() method (#101)
1 parent fe0c4d0 commit 3687058

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

trantor/unittests/DateUnittest.cc

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ TEST(Date, constructorTest)
2323
.toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true)
2424
.c_str());
2525
}
26+
TEST(Date, DatabaseStringTest)
27+
{
28+
auto now = trantor::Date::now();
29+
EXPECT_EQ(now, trantor::Date::fromDbStringLocal(now.toDbStringLocal()));
30+
std::string dbString = "2018-01-01 00:00:00.123";
31+
auto dbDate = trantor::Date::fromDbStringLocal(dbString);
32+
auto ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000;
33+
EXPECT_EQ(ms, 123);
34+
dbString = "2018-01-01 00:00:00";
35+
dbDate = trantor::Date::fromDbStringLocal(dbString);
36+
ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000;
37+
EXPECT_EQ(ms, 0);
38+
}
2639
int main(int argc, char **argv)
2740
{
2841
testing::InitGoogleTest(&argc, argv);

trantor/utils/Date.cc

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -293,10 +293,19 @@ Date Date::fromDbStringLocal(const std::string &datetime)
293293
{
294294
hour = std::stol(time[0]);
295295
minute = std::stol(time[1]);
296-
second = std::stol(time[2]);
297-
if (3 < time.size())
296+
auto seconds = splitString(time[2], ".");
297+
second = std::stol(seconds[0]);
298+
if (1 < seconds.size())
298299
{
299-
microSecond = std::stol(time[3]);
300+
if (seconds[1].length() > 6)
301+
{
302+
seconds[1].resize(6);
303+
}
304+
else if (seconds[1].length() < 6)
305+
{
306+
seconds[1].append(6 - seconds[1].length(), '0');
307+
}
308+
microSecond = std::stol(seconds[1]);
300309
}
301310
}
302311
}

0 commit comments

Comments
 (0)