Skip to content

Commit fea4b4f

Browse files
Fix date_time_with_ms millisecond formatting (ros2#570)
Signed-off-by: Mark Jin <mark@pixmoving.net>
1 parent ee1f1a2 commit fea4b4f

2 files changed

Lines changed: 9 additions & 9 deletions

File tree

‎src/time.c‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,7 @@ rcutils_time_point_value_as_date_string(
6363
// break into two parts to avoid floating point error
6464
uint64_t seconds = abs_time_point / (1000u * 1000u * 1000u);
6565
uint64_t nanoseconds = abs_time_point % (1000u * 1000u * 1000u);
66-
// Make sure the buffer is large enough to hold the largest possible uint64_t
67-
char nanoseconds_str[21];
68-
69-
if (rcutils_snprintf(nanoseconds_str, sizeof(nanoseconds_str), "%" PRIu64, nanoseconds) < 0) {
70-
RCUTILS_SET_ERROR_MSG("failed to format time point nanoseconds into string");
71-
return RCUTILS_RET_ERROR;
72-
}
66+
uint64_t milliseconds = nanoseconds / (1000u * 1000u);
7367

7468
time_t now_t = (time_t)(seconds);
7569
struct tm ptm = {.tm_year = 0, .tm_mday = 0};
@@ -91,8 +85,8 @@ rcutils_time_point_value_as_date_string(
9185
}
9286
static const int date_end_position = 19;
9387
if (rcutils_snprintf(
94-
&str[date_end_position], str_size - date_end_position, ".%.3s",
95-
nanoseconds_str) < 0)
88+
&str[date_end_position], str_size - date_end_position, ".%03" PRIu64,
89+
milliseconds) < 0)
9690
{
9791
RCUTILS_SET_ERROR_MSG("failed to format time point into string as date_time_with_ms");
9892
return RCUTILS_RET_ERROR;

‎test/test_time.cpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ TEST_F(TestTimeFixture, test_rcutils_time_point_value_as_date_string) {
357357
ss2 >> std::get_time(&t, "%Y-%b-%d %H:%M:%S");
358358
ASSERT_TRUE(ss2.fail());
359359

360+
// Subsecond values should be formatted as milliseconds, including leading zeros.
361+
timepoint = RCUTILS_S_TO_NS(1) + RCUTILS_MS_TO_NS(85) + RCUTILS_US_TO_NS(860);
362+
ret = rcutils_time_point_value_as_date_string(&timepoint, buffer, sizeof(buffer));
363+
EXPECT_EQ(RCUTILS_RET_OK, ret) << rcutils_get_error_string().str;
364+
EXPECT_STREQ(".085", buffer + 19);
365+
360366
// nullptr for timepoint
361367
ret = rcutils_time_point_value_as_date_string(nullptr, buffer, sizeof(buffer));
362368
EXPECT_EQ(RCUTILS_RET_INVALID_ARGUMENT, ret);

0 commit comments

Comments
 (0)