C++和C下时间格式化如YYYYMMDD HH:mm:mm.fff支持win和Linux
#ifndef _ANJOS_KEBA_
#define _ANJOS_KEBA_
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <fstream>
#include <time.h>
#ifdef _WIN32
#include <ctime>
#include <Windows.h>
#include <cstring>
#else
#include <sys/time.h>
#endif
/**
* 格式化字符串
*/
template< typename... Args > std::string strsprintf(const char* format, Args... args) {
int length = std::snprintf(nullptr, 0, format, args...);
assert(length >= 0);
char* buf = new char[length + 1];
std::snprintf(buf, length + 1, format, args...);
std::string str(buf);
delete[] buf;
return str;
}
#ifdef _WIN32
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* and microseconds */
};
inline int gettimeofday(struct timeval *tp, void* tzp){
time_t clock;
struct tm tm;
SYSTEMTIME wtm;
GetLocalTime(&wtm);
tm.tm_year = wtm.wYear - 1900;
tm.tm_mon = wtm.wMonth - 1;
tm.tm_mday = wtm.wDay;
tm.tm_hour = wtm.wHour;
tm.tm_min = wtm.wMinute;
tm.tm_sec = wtm.wSecond;
tm.tm_isdst = -1;
clock = mktime(&tm);
tp->tv_sec = clock;
tp->tv_usec = wtm.wMilliseconds * 1000;
return (0);
}
#endif
inline std::string now2str() {
time_t tt = time(NULL);//这句返回的只是一个时间戳
struct timeval tv;
gettimeofday(&tv, NULL);
tm* t = localtime(&tt);
long milliseconds = tv.tv_usec / 1000;
char* time_str = new char[40];
sprintf(time_str, "%d-%02d-%02d %02d:%02d:%02d.%03ld",
t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, milliseconds);//输出格式为: 20200717 105228.302
//delete t;
std::string time_full_str(time_str);
delete[] time_str;
return time_full_str;
}
#endif
这里要特别注意,now2str()返回的是std::string格式,得用std::cout打印,若用printf打印则是乱码的,printf只支持char*打印
测试方法如下:
int main(void){
std::string now = now2str();
std::cout<<"当前时间为"<<now<<std::endl;
printf( "当前时间=%s\r\n", now.c_str() ):
}