Reputation: 101
I am trying to find a solution on outputting current date and time (with milliseconds) in the following format: 2018-01-28 15:51:02.159
This could be solved using using C++17 and chrono::floor<chrono::seconds>
or C++11 std::chrono::duration_cast<std::chrono::seconds>
Unfortunately I cannot use C++17 or C++11 - are there any other not too advanced options out there? If not, I would appreciate some help in getting the formatting correct without fractional time, like this: 2018-01-28 15:51:02
Help is very much appreciated!
Upvotes: 1
Views: 179
Reputation: 8047
Using localtime and this post Getting current time with milliseconds:
#include <time.h>
#include <cstdio> // handle type conversions
#include <sys/time.h>
int main (void) {
timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
char buffer [80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));
char currentTime[84] = "";
sprintf(currentTime, "%s.%d", buffer, milli);
printf("current date time: %s \n", currentTime);
return 0;
}
outputs:
current date time: 2018-01-28 14:45:52.486
Upvotes: 1
Reputation: 3776
As C++ inherits it's time units from C a guaranteed solution is to fall back to the C library (can't remember seeing a pure C++ version... this keeps as much C++ as I can):
#include <iostream>
#include <iomanip> // std::setw()...
#include <cstdlib>
#include <sys/time.h> // gettimeofday() and friends
int main(void)
{
struct timeval tv;
struct tm local_tm;
char print_time[30];
gettimeofday(&tv,NULL);
localtime_r( &tv.tv_sec, &local_tm );
strftime( print_time, sizeof print_time, "%Y-%m-%d %H:%M:%S.", &local_tm );
std::cout << print_time << std::setw(3) << std::setfill('0') << ( tv.tv_usec + 500 ) / 1000 << std::endl;
return EXIT_SUCCESS;
}
You could of course skip strftime() by a series of setw() calls, but I think strftime() is cleaner.
Upvotes: 1