After discussing in the comments exactly what you were after, I came up with this:
size_t MkTimestamp(char *output, size_t size)
{
milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
seconds s = duration_cast<seconds>(ms);
time_t ctime = (time_t) s.count();
tm components;
size_t return_value = 0;
if (!localtime_r(&ctime, &components)) return 0;
if ((return_value = strftime(output, size, "%F %T:XXX", &components)) == 0) return 0;
int ms_d1 = ms.count() / 100 % 10, ms_d2 = ms.count() / 10 % 10, ms_d3 = ms.count() % 10;
output[return_value - 3] = ms_d1 + '0';
output[return_value - 2] = ms_d2 + '0';
output[return_value - 1] = ms_d3 + '0';
return return_value;
}
In short, you give it a character buffer and its size, and it writes a timestamp to it (if the buffer is too small, it returns zero, otherwise it returns the total number of characters it wrote, including the null terminator). If you wanted this timestamp as a std::string
, you could use the std::string
slice constructor:
char buffer[64];
string timestamp(buffer, MkTimestamp(buffer, sizeof buffer));
The string constructor will read until the null terminator if MkTimestamp succeeds, and will produce an empty string if it fails. You could probably consolidate this step into MkTimestamp
if you wanted to.
This is different from your first try in the following way:
- Since you're trying to produce a timestamp, you're better off using absolute, rather than relative, time.
- Since we want to use absolute time, we must use
system_clock
, because this is the only clock that actually gives time_point
values that can be meaningfully converted into time_t
values that the old C family functions will accept. (Sometimes, these two clocks have the same epoch, or are even the same clock. But not always.)
- I picked a different time format. You can change that if you want, it won't be hard. I highly recommend that you keep the millisecond placeholders in the format string, so you don't have to do any length tests as long as
strftime
succeeds.
Credit where credit is due (other stackoverflow answers that I referenced while writing this answer)
Original answer:
Here's an ideone with your code. (Notice that the issue you describe does not occur.) Also, you're missing #include <thread>
.
That aside, the documentation for ctime()
indicates that its argument is expected to be a calender date. You're passing it an interval of one second, which is more or less meaningless by itself. You're probably right that it's showing exactly one hour off because of a time zone interpretation issue.
I can't answer any better without more details about what you're actually trying to do.