C++獲取當前時間(年月日、時分秒、毫秒)
阿新 • • 發佈:2019-01-23
獲取時間:
年-月-日(YYmmdd)
時:分:秒(HHMMSS)
毫秒(MS)
效率問題需要再優化
程式碼:
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
struct NowDate
{
char tmp0[16]; //年月日
char tmp1[16]; //時分秒
char tmp2[4]; //毫秒
};
NowDate getTime()
{
time_t timep;
time (&timep);
NowDate date;
strftime(date.tmp0, sizeof (date.tmp0), "%Y-%m-%d",localtime(&timep) );
strftime(date.tmp1, sizeof(date.tmp1), "%H:%M:%S",localtime(&timep) );
struct timeb tb;
ftime(&tb);
sprintf(date.tmp2,"%d",tb.millitm);
return date;
}
int main()
{
NowDate time = getTime();
cout << time.tmp0 <<endl;
cout << time.tmp1 <<endl;
cout << time.tmp2 <<endl;
return 0;
}
結果: