Created
August 28, 2024 17:15
-
-
Save slyshykO/978de55863529ab7077a613302350e80 to your computer and use it in GitHub Desktop.
Format current time in this form: "hh:mm:ss.SSS" (where "SSS" are milliseconds) (C++)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//----------------------------------------------------------------------------- | |
// Format current time (calculated as an offset in current day) in this form: | |
// | |
// "hh:mm:ss.SSS" (where "SSS" are milliseconds) | |
//----------------------------------------------------------------------------- | |
std::string now_str() | |
{ | |
// Get current time from the clock, using microseconds resolution | |
const boost::posix_time::ptime now = | |
boost::posix_time::microsec_clock::local_time(); | |
// Get the time offset in current day | |
const boost::posix_time::time_duration td = now.time_of_day(); | |
// | |
// Extract hours, minutes, seconds and milliseconds. | |
// | |
// Since there is no direct accessor ".milliseconds()", | |
// milliseconds are computed _by difference_ between total milliseconds | |
// (for which there is an accessor), and the hours/minutes/seconds | |
// values previously fetched. | |
// | |
const long hours = td.hours(); | |
const long minutes = td.minutes(); | |
const long seconds = td.seconds(); | |
const long milliseconds = td.total_milliseconds() - | |
((hours * 3600 + minutes * 60 + seconds) * 1000); | |
// | |
// Format like this: | |
// | |
// hh:mm:ss.SSS | |
// | |
// e.g. 02:15:40:321 | |
// | |
// ^ ^ | |
// | | | |
// 123456789*12 | |
// ---------10- --> 12 chars + \0 --> 13 chars should suffice | |
// | |
// | |
char buf[40]; | |
sprintf(buf, "%02ld:%02ld:%02ld.%03ld", | |
hours, minutes, seconds, milliseconds); | |
return buf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment