我们经常需要获取当前时间,几种常用的方法介绍如下:
1.方式一:利用GetLocalTime()函数
#include <Windows.h>
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
SYSTEMTIME sTime;
GetLocalTime(&sTime);
char szTime[64]={0};
sprintf_s(szTime,sizeof(szTime),"%04d/%02d/%02d %02d:%02d:%02d:%03d",sTime.wYear,sTime.wMonth,sTime.wDay,sTime.wHour,sTime.wMinute,sTime.wSecond,sTime.wMilliseconds);
cout<<szTime<<endl;
return 0;
}
2017/12/07 11:27:59:107
请按任意键继续. . .
2.方式二:利用localtime()函数
#include <iostream>
using namespace std;
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm* stime=localtime(&t);
char szTime[64]={NULL};
sprintf_s(szTime,sizeof(szTime),"%04d-%02d-%02d %02d:%02d:%02d",1900+stime->tm_year,1+stime->tm_mon,
stime->tm_mday, stime->tm_hour,
stime->tm_min,stime->tm_sec);
cout<<szTime<<endl;
return 0;
}
2017-12-07 11:30:25
请按任意键继续. . .
3.方式三:利用strftime格式化时间输出
#include <iostream>
using namespace std;
#include <time.h>
int main()
{
time_t t = time(0);
char szTime[64]={NULL};
strftime(szTime, sizeof(szTime), "%Y-%m-%d %H:%M:%S",localtime(&t));
cout<<szTime<<endl;
return 0;
}
2017-12-07 11:31:13
请按任意键继续. . .
4.方式四:利用ctime日历时间法输出
#include <iostream>
using namespace std;
#include <time.h>
#include <string>
int main()
{
time_t tm;
time(&tm);
char szTime[64]={NULL};
strcpy(szTime,ctime(&tm));
//或者
//struct tm* stime=localtime(&tm);
//strcpy(szTime,asctime(stime));
cout<<szTime<<endl;
return 0;
}
Thu Dec 07 11:32:21 2017
请按任意键继续. . .