#include <iostream>
#include <time.h>
#include <string>
#if _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif
#include <windows.h>
using namespace std;
/**
time_t strtotime(const char* date,const char* format="%Y%m%d%H%M%S")
{
struct tm tm;
strptime(date,format, &tm);
time_t ft=mktime(&tm);
return ft;
}
*/
string timetodate(time_t const timer)
{
struct tm *l=localtime(&timer);
char buf[128];
snprintf(buf,sizeof(buf),"%04d-%02d-%02d %02d:%02d:%02d",l->tm_year+1900,l->tm_mon+1,l->tm_mday,l->tm_hour,l->tm_min,l->tm_sec);
string s(buf);
return s;
}
std::string getNowTime()
{
time_t nowtime=time(NULL);
struct tm *l=localtime(&nowtime);
char buf[128];
snprintf(buf,sizeof(buf),"%04d-%02d-%02d %02d:%02d:%02d",l->tm_year+1900,l->tm_mon+1,l->tm_mday,l->tm_hour,l->tm_min,l->tm_sec);
std::string s(buf);
return s;
}
std::string getTime()
{
time_t timep;
time (&timep);
char tmp[64];
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );
return std::string(tmp);
}
long GetMilliseconds()
{
#if _WIN32
long millisecond=GetTickCount();
return millisecond;//?
#else
struct timeval tv;
gettimeofday(&tv,NULL);
long millisecond=tv.tv_sec*1000 + tv.tv_usec/1000;
//printf("millisecond:%ld\n",millisecond);
return millisecond;
#endif
}
/**
std::string getTimeByCpp11()
{
time_t t = time(nullptr);
tm tm = *localtime(&t);
std::cout.imbue(locale("ru_RU.utf8"));
std::string nowtime=std::put_time(&tm, "%c %Z")
std::cout << "ru_RU: " << << '\n'; // %Y-%m-%d %H:%M:%S
return nowtime;
}
*/
//要改变input的数据,传引用进去
void hehe(std::string &input)
{
input=input+" hehe 1024";
}
char* getbuildtime()
{
#define YEAR ((((__DATE__ [7] - '0') * 10 + (__DATE__ [8] - '0')) * 10 \
+ (__DATE__ [9] - '0')) * 10 + (__DATE__ [10] - '0'))
#define MONTH (__DATE__ [2] == 'n' ? 0 \
: __DATE__ [2] == 'b' ? 1 \
: __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? 2 : 3) \
: __DATE__ [2] == 'y' ? 4 \
: __DATE__ [2] == 'n' ? 5 \
: __DATE__ [2] == 'l' ? 6 \
: __DATE__ [2] == 'g' ? 7 \
: __DATE__ [2] == 'p' ? 8 \
: __DATE__ [2] == 't' ? 9 \
: __DATE__ [2] == 'v' ? 10 : 11)
#define DAY ((__DATE__ [4] == ' ' ? 0 : __DATE__ [4] - '0') * 10 \
+ (__DATE__ [5] - '0'))
#define DATE_AS_INT (((YEAR - 2000) * 12 + MONTH) * 31 + DAY)
//LOGD_STRING("version:"+StringUtils::float2str(VERIONS_CODE)+__DATE__);
static char buildtime[256]={0};
//sprintf(buildtime,"build time:%d-%02d-%02d",YEAR, MONTH + 1, DAY);
sprintf(buildtime,"%d-%02d-%02d %s",YEAR, MONTH + 1, DAY,__TIME__);
// printf("%s\n",buildtime);
return buildtime;
}
//c/c++实现格式化时间函数
int main(int argc, char** argv)
{
cout << "build time:"<<getbuildtime() << endl;
time_t nowtime=time(NULL);
string now=timetodate(nowtime);
cout<<now<<endl;
cout<<getNowTime()<<endl;
string data=getNowTime();
cout<<data<<endl;
hehe(data);
cout<<data<<endl;
string time = getTime();
cout << time<<"<=c++ time" << endl;
cout<<GetMilliseconds()<<endl;
//cout<<getTimeByCpp11()<<endl;
return 0;
}
c/c++实现格式化时间函数
最新推荐文章于 2024-06-14 21:03:26 发布