C语言获取13位时间戳以及格式化时间戳

定义time_util.h头文件

#ifndef TIME_UTIL_H
#define TIME_UTIL_H
#include 
#include 
#ifdef _WIN32
#include 
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
#include 
#endif

void get_timestamp_str(char* timebuf);
long long get_timestamp_dlg();

#endif

定义源文件
time_util.cpp

#include "time_util.h"

void get_timestamp_str(char* timebuf) {
    time_t rawtime;
    struct tm* timeinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(timebuf, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
}


long long get_timestamp_dlg() {
#ifdef _WIN32
    FILETIME ft;
    GetSystemTimeAsFileTime(&ft);
    unsigned long long tmpres = 0;
    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;
    tmpres /= 10;  //convert into microseconds
    tmpres -= DELTA_EPOCH_IN_MICROSECS;
    return tmpres / 1000; // Convert into milliseconds
#else
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return ((long long)tv.tv_sec * 1000LL + (long long)tv.tv_usec / 1000LL);
#endif
}

可在main函数中测试:

#include 
#include "time_util.h"
int main(){
	char btime[80];
	for (int i = 0; i < 100; i++) {
		get_timestamp_str(btime);
		long long timx = get_timestamp_dlg();
		std::cout << btime << std::endl;
		std::cout << timx << std::endl;
	}
	return 0;
}

展示:
C语言获取13位时间戳以及格式化时间戳_第1张图片

你可能感兴趣的:(c语言,开发语言)