Currently I use this code
string now() {
time_t t = time(0);
char buffer[9] = {0};
strftime(buffer, 9, "%H:%M:%S", localtime(&t));
return string(buffer);
}
to format time. I need to add milliseconds, so the output has the format: 16:56:12.321
Here is a solution I found without using boost
I'd recommend to use Boost.Chrono instead of Boost.Datetime library because Chrono became a part of C++11. Examples here
Don't waste your time with Boost (I know many will be offended by this statement and consider it heresy).
This discussion contains two very workable solutions that don't require you to enslave yourself to non-standard, 3rd party libraries.
C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly
http://linux.die.net/man/3/clock_gettime
References to gettimeofday can be found here at opengroup.org
You can use Boost's Posix Time.
You can use
boost::posix_time::microsec_clock::local_time()
to get current time from microseconds-resolution clock:Then you can compute time offset in current day (since your duration output is in the form
<hours>:<minutes>:<seconds>.<milliseconds>
, I'm assuming they are calculated as current day offset; if they are not, feel free to use another starting point for duration/time interval):Then you can use
.hours()
,.minutes()
,.seconds()
accessors to get the corresponding values.Unfortunately, there doesn't seem to be a
.milliseconds()
accessor, but there is a.total_milliseconds()
one; so you can do a little subtraction math to get the remaining milliseconds to be formatted in the string.Then you can use
sprintf()
(orsprintf()_s
if you are interested in non-portable VC++-only code) to format those fields into a rawchar
buffer, and safely wrap this raw C string buffer into a robust convenientstd::string
instance.See the commented code below for further details.
Output in console is something like:
Sample code:
You can use
boost::posix_time
. See this SO question. Ex:To get the current time:
You can also use the C++11 chrono, if you can use C++11. Ex:
To get the current time (you have several different clocks available, see the doc):
For the time in milliseconds, you can get the duration between midnight and the current time. Example with std::chrono: