以下提供两种方法获取Windows系统的开机时间
第一种是使用C++的函数,该方法使用当前时间减去系统运行时间,秒级的,偶尔存在1秒的差异
第二种是使用Windows的API,该方法获取到的时间与cmd命令systeminfo获取的时间是一致的,故推荐使用这种方法获取系统开机时间
1、C++
void GetSystemUpTime()
{
DWORD iRunTime = GetTickCount();
const int Num1 = 1000;
const int Num2 = 1900;
time_t nowTime;
time(&nowTime);
time_t systemUpTime = nowTime - (iRunTime / Num1);
struct tm * timeInfo;
timeInfo = localtime(&systemUpTime);
printf("开机时间: %d-%d-%d %02d:%02d:%02d",timeInfo->tm_year + Num2,
timeInfo->tm_mon + 1, timeInfo->tm_mday, timeInfo->tmhour,
timeInfo->tm_min, timeInfo->tm_sec);
}
2、
#include<stdio.h>
#include<windows.h>
#define NT_SUCCESS(x) ((x)>=0)
const UINT SystemTimeInformation = 3;
typedef struct {
LARGE_INTEGER liKeBootTime;
LARGE_INTEGER liKeSystemTime;
LARGE_INTEGER liExpTimeZoneBias;
ULONG uCurrentTimeZoneId;
DWORD dwReserved;
} SYSTEM_TIME_INFORMATION;
typedef long (__stdcall *fnNtQuerySystemInformation)(
IN UINT SystemInformationClass,
OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength OPTIONAL);
static fnNtQuerySystemInformation NtQuerySystemInformation = NULL;
int main(void)
{
NtQuerySystemInformation = (fnNtQuerySystemInformation)GetProcAddress(LoadLibrary("ntdll.dll"),
"NtQuerySystemInformation");
if(NtQuerySystemInformation == NULL)
{
printf("Get NtQuerySystemInformation Addr Failed,err=%u\n",GetLastError());
return 0;
}
LONG status;
SYSTEM_TIME_INFORMATION sti;
status = NtQuerySystemInformation(SystemTimeInformation, &sti,sizeof(sti),0);
if(NO_ERROR != status)
{
printf("NtQuerySystemInformation Failed!n");
return 0;
}
FILETIME ft1,ft2;
SYSTEMTIME st;
memcpy_s(&ft1, sizeof(ft1),&sti.liKeBootTime,sizeof(sti.liKeBootTime));
//将其转为文件时间
//将一个FILETIME结构转换成本地时间
if(0 == FileTimeToLocalFileTime(&ft1,&ft2))
{
printf("FileTimeToLocalFileTime Failed err=%u\nn",GetLastError());
return 0;
}
//将文件时间转为系统时间
if(0 == FileTimeToSystemTime(&ft2,&st))
{
printf("FileTimeToSystemTimeFailed err=%u\nn",GetLastError());
return 0;
}
printf("Date: %02d-%02d-%04d Time: %02d:%02d:%02d ",st.wMonth,st.wDay,st.wYear, st.wHour,st.wMinute,st.wSecond);
getchar();
return 0;
}
参考:
https://wwwblogs/fengbohello/p/4277082.html
https://blog.csdn/cxq_1993/article/details/48024193