Created
August 25, 2016 01:45
-
-
Save liangfu/badee2700b3c9d8ba654834cd8119396 to your computer and use it in GitHub Desktop.
Get current time in formatted string with cross-platform C/C++, while avoid using c++11 classes.
This file contains 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
#include <string> | |
#include <ctime> | |
#if defined WIN32 | |
#include <windows.h> | |
#include <stdint.h> | |
static int gettimeofday(struct timeval * tp, struct timezone * tzp) | |
{ | |
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's | |
static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL); | |
SYSTEMTIME system_time; | |
FILETIME file_time; | |
uint64_t time; | |
GetSystemTime( &system_time ); | |
SystemTimeToFileTime( &system_time, &file_time ); | |
time = ((uint64_t)file_time.dwLowDateTime ) ; | |
time += ((uint64_t)file_time.dwHighDateTime) << 32; | |
tp->tv_sec = (long) ((time - EPOCH) / 10000000L); | |
tp->tv_usec = (long) (system_time.wMilliseconds * 1000); | |
return 0; | |
} | |
#endif | |
static const char * currentTime() { | |
time_t now = time(0); | |
struct tm tstruct; | |
char buf[80]={0,}; | |
tstruct = *localtime(&now); | |
strftime(buf, sizeof(buf), "%H:%M:%S", &tstruct); | |
int milli = 0; | |
timeval curTime; | |
gettimeofday(&curTime, NULL); | |
milli = curTime.tv_usec / 1000; | |
char currTime[84] = {0,}; | |
sprintf(currTime, "%s:%d", buf, milli); | |
return currTime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment