@@ -205,7 +205,37 @@ nlohmann::json ElasticSearchRecordable::GetJSON() noexcept
205205void ElasticSearchRecordable::SetTimestamp (
206206 opentelemetry::common::SystemTimestamp timestamp) noexcept
207207{
208- json_[" timestamp" ] = timestamp.time_since_epoch ().count ();
208+ // If built with with at least cpp 20 then use std::format
209+ // Otherwise use the old style to format the timestamp in UTC
210+ #if __cplusplus >= 202002L
211+ const std::chrono::system_clock::time_point timePoint{timestamp};
212+ const std::string dateStr = std::format (" {:%FT%T%Ez}" , timePoint);
213+ #else
214+ const static int dateToSecondsSize = 19 ;
215+ const static int millisecondsSize = 6 ;
216+ const static int timeZoneSize = 1 ;
217+ const static int dateSize = dateToSecondsSize + millisecondsSize + timeZoneSize;
218+
219+ std::time_t time = std::chrono::system_clock::to_time_t (timestamp);
220+ std::tm tm = *std::gmtime (&time);
221+
222+ char bufferDate[dateSize]; // example: 2024-10-18T07:26:00.123456Z
223+ std::strftime (bufferDate, sizeof (buffer), " %Y-%m-%dT%H:%M:%S" , &tm);
224+ auto microseconds =
225+ std::chrono::duration_cast<std::chrono::microseconds>(timestamp.time_since_epoch ()) %
226+ std::chrono::seconds (1 );
227+
228+ char bufferMilliseconds[millisecondsSize];
229+ std::snprintf (bufferMilliseconds, sizeof (bufferMilliseconds), " .%06ld" ,
230+ static_cast <long >(microseconds.count ()));
231+
232+ std::strcat (bufferDate, bufferMilliseconds);
233+ std::strcat (buffer, " Z" );
234+
235+ const std::string dateStr (buffer);
236+ #endif
237+
238+ json_[" @timestamp" ] = dateStr;
209239}
210240
211241void ElasticSearchRecordable::SetObservedTimestamp (
0 commit comments