I'm working on a logging system for my console, and I'm trying to get a timestamp for when a entry was added to the log. I tried doing this;
time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char time_buffer[16] = { 0 };
std::strftime(time_buffer, sizeof(time_buffer), "%H.%M.%S", std::localtime(&now));
TextWrapped(time_buffer);
This almost works. The issue is that this works more as a clock then as a timestamp as it will not stay at the time of when the entry was logged, but increment... I think that I might have to use std::chrono::time_point, but I didn't really understand how to use it.
CodePudding user response:
In C 20 there are a number of nice functions in std::chrono to do this:
#include <iostream>
#include <chrono>
#include <format>
int main()
{
// get the current time
auto now = std::chrono::system_clock::now();
// floor till the start of day
auto start_of_day = std::chrono::floor<std::chrono::days>(now);
// round time till nearest seconds
auto time_since_start_of_day = std::chrono::round<std::chrono::seconds>(now - start_of_day);
// convert to hour minute second type
std::chrono::hh_mm_ss hms { time_since_start_of_day };
std::cout << time_since_start_of_day << "\n"; // will output number of seconds since start of day
std::cout << hms << "\n"; // will output formatted time in hh:mm::ss
auto string = std::format("{}", hms);
std::cout << string << "\n"; // will output formatted time in hh:mm::ss
return 0;
}
CodePudding user response:
So I figured it out. The issue is that since my code snipped is in my render function, it will always update. My fix was to move the snippet above into my "add_log()" function, then write those timestamps into a new array, then in my for loop I would just grab from both arrays. Kinda like so;
for (int i = 0; i < items.Size; i ) {
TextWrapped(items[i]);
TextWrapped(timestamps[i]);
}
It's a hacky solution, but it works.
