C/C++获取系统时间
背景
在编程过程中,经常需要获取系统时间,例如记录日志或数据的时候,需要把时间也记录下来,现在介绍C/C++获取系统时间的几种方法吧。
(1)MFC方法,只适合Windows MFC/ATL编程
CTime time = CTime::GetCurrentTime();
CString str = time.Format("%Y-%m-%d %H:%M:%S");
(2)C方法,适用于Windows和Linux和嵌入式
#incldue <stdio.h>
#include <time.h>
#include <string.h>
int main(int argc, char * argv[])
{
time_t tt;
time(&tt);
struct tm tms;
localtime_s(&tms, &tt);
char str[20];
snprintf(str, sizeof(str), "%d-%02d-%02d",
tms.tm_year + 1900, tms.tm_mon + 1, tms.tm_mday,
tms.tm_hour, tms.tm_minute, tms.tm_second);
printf("Current time is : %s", str);
}
C++方法,适用于Windows和Linux
#include <iostream>
#include <ctime>
#include <cstring>
using std::chrono::system_clock;
int main(int argc, char * argv[])
{
char str[20];
system_clock::time_point today = system_clock::now();
std::time_t tt;
tt = system_clock::to_time_t(today);
struct tm stm;
localtime_s(&stm, &tt);
strftime(str, sizeof(str), "%F %T", &stm);
std::cout << "Current time is : " << str << std::endl;
return 0;
}