Skip to content

Commit c29e243

Browse files
committed
[#24281] Simplified UTC offset conversion for %Z
Signed-off-by: danipiza <dpizarrogallego@gmail.com>
1 parent 911d628 commit c29e243

1 file changed

Lines changed: 56 additions & 33 deletions

File tree

cpp_utils/src/cpp/time/time_utils.cpp

Lines changed: 56 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
#include <iomanip>
2121
#include <thread>
2222
#include <sstream>
23-
#include <cstdio>
2423

2524
#include <cpp_utils/macros/macros.hpp>
2625
#include <cpp_utils/time/time_utils.hpp>
@@ -36,6 +35,61 @@
3635
namespace eprosima {
3736
namespace utils {
3837

38+
static std::string utc_offset_string(
39+
const std::tm& tm,
40+
bool local_time)
41+
{
42+
if (!local_time)
43+
{
44+
return "UTC+00";
45+
}
46+
47+
std::ostringstream os;
48+
os << std::put_time(&tm, "%z");
49+
const std::string z = os.str();
50+
51+
if (z.empty() || (z[0] != '+' && z[0] != '-'))
52+
{
53+
return "UTC+00";
54+
}
55+
56+
std::string hh;
57+
std::string mm = "00";
58+
59+
// +HH
60+
if (z.size() == 3)
61+
{
62+
hh = z.substr(1, 2);
63+
}
64+
// +HHMM
65+
else if (z.size() == 5)
66+
{
67+
hh = z.substr(1, 2);
68+
mm = z.substr(3, 2);
69+
}
70+
// +HH:MM
71+
else if (z.size() == 6 && z[3] == ':')
72+
{
73+
hh = z.substr(1, 2);
74+
mm = z.substr(4, 2);
75+
}
76+
else
77+
{
78+
return "UTC+00";
79+
}
80+
81+
std::string ret = "UTC";
82+
ret += z[0];
83+
ret += hh;
84+
if (mm != "00")
85+
{
86+
ret += ":";
87+
ret += mm;
88+
}
89+
90+
return ret;
91+
}
92+
3993
Timestamp now() noexcept
4094
{
4195
return Timeclock::now();
@@ -118,38 +172,7 @@ std::string timestamp_to_string(
118172
{
119173
if (format[i] == '%' && i + 1 < format.size() && format[i + 1] == 'Z')
120174
{
121-
long offset_sec = 0;
122-
if (local_time)
123-
{
124-
#if _EPROSIMA_WINDOWS_PLATFORM
125-
// _timezone: seconds west of UTC for standard time (negative when east of UTC)
126-
offset_sec = -(long)_timezone;
127-
if (tm->tm_isdst > 0)
128-
{
129-
// _dstbias: adjustment in seconds when DST is active (typically -3600)
130-
offset_sec -= (long)_dstbias;
131-
}
132-
#else
133-
// tm_gmtoff: seconds east of UTC, set by localtime()
134-
offset_sec = tm->tm_gmtoff;
135-
#endif // _EPROSIMA_WINDOWS_PLATFORM
136-
}
137-
138-
const char sign = (offset_sec >= 0) ? '+' : '-';
139-
const long abs_offset = (offset_sec >= 0) ? offset_sec : -offset_sec;
140-
const long hours = abs_offset / 3600;
141-
const long minutes = (abs_offset % 3600) / 60;
142-
143-
char buf[16];
144-
if (minutes != 0)
145-
{
146-
snprintf(buf, sizeof(buf), "UTC%c%02ld:%02ld", sign, hours, minutes);
147-
}
148-
else
149-
{
150-
snprintf(buf, sizeof(buf), "UTC%c%02ld", sign, hours);
151-
}
152-
processed_format += buf;
175+
processed_format += utc_offset_string(*tm, local_time);
153176
++i;
154177
}
155178
else

0 commit comments

Comments
 (0)