C++获取系统时间
方法1:
GetLocalTime是一个Windows API 函数,用来获取当地的当前系统日期和时间。
函数原型:
VOID GetLocalTime(
LPSYSTEMTIME lpSystemTime //address of system times structure
);
参数说明:
lpSystemTime: 指向一个用户自定义包含日期和时间信息的类型为 SYSTEMTIME 的变量,该变量用来保存函数获取的时间信息。
此函数会把获取的系统时间信息存储到SYSTEMTIME结构体里边
typedef struct _SYSTEMTIME
{
WORD wYear;//年
WORD wMonth;//月
WORD wDayOfWeek;//星期,0为星期日,1为星期一,2为星期二……
WORD wDay;//日
WORD wHour;//时
WORD wMinute;//分
WORD wSecond;//秒
WORD wMilliseconds;//毫秒
}SYSTEMTIME,*PSYSTEMTIME;
#include<stdio.h>
#include<windows.h>
#include<winbase.h>
intmain(intargc,char*argv[])
{
SYSTEMTIME time;
GetLocalTime(&time);
printf("当前时间为:%2d:%2d:%2d\n",time.wHour,time.wMinute,time.wSecond);
return0;
}
方法2:
time() 是指返回自 Unix 纪元(January 1 1970 00:00:00 GMT)起的当前时间的秒数的函数,主要用来获取当前的系统时间,返回的结果是一个time_t类型。
#include<stdio.h>
#include<windows.h>
#include<winbase.h>
intmain(intargc,char*argv[])
{
time_t tt = time(NULL);//这句返回的只是一个时间cuo
tm* t= localtime(&tt);
printf("%d-%02d-%02d %02d:%02d:%02d\n",
t->tm_year + 1900,
t->tm_mon + 1,
t->tm_mday,
t->tm_hour,
t->tm_min,
t->tm_sec);
return0;
}