使用的API
Windows API | 功能简述 |
---|---|
GetLocalTime | 获取本地系统时间 |
SetLocalTime | 修改系统时间 |
GetTickCount | 获取系统运行时间 |
GetTickCount64 | 获取系统运行时间 |
获取本地系统时间
使用GetLocalTime
代码
#include <Windows.h>
#include <stdio.h>
int main() {
SYSTEMTIME st;
// 获取本地系统时间
GetLocalTime(&st);
printf("Now: %d-%#02d-%#02d, %#02d:%#02d:%#02d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return 0;
}
运行效果
修改系统时间
使用SetLocalTime
,我运行下面的代码没有效果,没设置成功
代码
#include <Windows.h>
#include <stdio.h>
int main() {
SYSTEMTIME st;
// 修改时间,将系统时间提前一个小时
st.wHour--;
SetLocalTime(&st);
return 0;
}
获取系统开机时间
使用GetTickCount64
代码
#include <Windows.h>
#include <stdio.h>
int main() {
// 开机到现在持续时间, 单位毫秒
DWORD c1 = GetTickCount(); // 当电脑开机时间较长时,32位保存不了,需要使用64位保存
ULONGLONG c2 = GetTickCount64(); // 返回64位,可以保存很长时间
printf("%ld %ld\n", c1, c2);
return 0;
}
运行效果
系统运行时间的另一个应用
可以用来作为随机数的种子
代码
#include <Windows.h>
#include <stdio.h>
#define total 10
int main() {
// 可以使用系统开机时间设置随机数的种子
srand(GetTickCount());
int nums[total];
for (size_t i = 0; i < total; i++)
{
nums[i] = rand() % 1000; // 1000以内的随机数
}
for (int i = 0; i < total; i++) {
printf("%d\n", nums[i]);
}
return 0;
}