Skip to content

Commit 8d50325

Browse files
committed
Update the Date class
1 parent 2bfc357 commit 8d50325

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

trantor/utils/Date.cc

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,37 @@ void Date::toCustomedFormattedString(const std::string &fmtStr, char *str, size_
7777
gmtime_r(&seconds, &tm_time);
7878
strftime(str, len, fmtStr.c_str(), &tm_time);
7979
}
80+
std::string Date::toFormattedStringLocal(bool showMicroseconds) const
81+
{
82+
// std::cout<<"toFormattedString"<<std::endl;
83+
char buf[128] = {0};
84+
time_t seconds = static_cast<time_t>(microSecondsSinceEpoch_ / MICRO_SECONDS_PRE_SEC);
85+
struct tm tm_time;
86+
localtime_r(&seconds, &tm_time);
87+
88+
if (showMicroseconds)
89+
{
90+
int microseconds = static_cast<int>(microSecondsSinceEpoch_ % MICRO_SECONDS_PRE_SEC);
91+
snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d",
92+
tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
93+
tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec,
94+
microseconds);
95+
}
96+
else
97+
{
98+
snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d",
99+
tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
100+
tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec);
101+
}
102+
return buf;
103+
}
104+
std::string Date::toCustomedFormattedStringLocal(const std::string &fmtStr) const
105+
{
106+
char buf[256] = {0};
107+
time_t seconds = static_cast<time_t>(microSecondsSinceEpoch_ / MICRO_SECONDS_PRE_SEC);
108+
struct tm tm_time;
109+
localtime_r(&seconds, &tm_time);
110+
strftime(buf, sizeof(buf), fmtStr.c_str(), &tm_time);
111+
return std::string(buf);
112+
}
80113
}; // namespace trantor

trantor/utils/Date.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ class Date
4242
struct tm tmStruct() const;
4343
std::string toFormattedString(bool showMicroseconds) const; //UTC
4444
std::string toCustomedFormattedString(const std::string &fmtStr) const; //UTC
45+
46+
std::string toFormattedStringLocal(bool showMicroseconds) const; //Local time zone
47+
std::string toCustomedFormattedStringLocal(const std::string &fmtStr) const; //Local time zone
48+
4549
void toCustomedFormattedString(const std::string &fmtStr, char *str, size_t len) const; //UTC
4650
bool isSameSecond(const Date &date) const
4751
{
@@ -54,8 +58,9 @@ class Date
5458
std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_);
5559
}
5660

57-
private:
5861
explicit Date(int64_t microSec) : microSecondsSinceEpoch_(microSec){};
62+
63+
private:
5964
int64_t microSecondsSinceEpoch_ = 0;
6065
};
6166
}; // namespace trantor

0 commit comments

Comments
 (0)