gpt4 book ai didi

c++ - 如何从 ULONGLONG 毫秒创建 SYSTEMTIME 结构?

转载 作者:可可西里 更新时间:2023-11-01 10:59:17 26 4
gpt4 key购买 nike

我不想使用 WMI 获取上次启动时间,而是想使用 ::GetSystemTime()::GetTickCount64 来计算它。但是一旦达到毫秒,我就不知道如何返回到 FILETIME 对象。

我试过这个:

static ULONGLONG FileTimeToMillis(const FILETIME &ft)
{
ULARGE_INTEGER uli;
uli.LowPart = ft.dwLowDateTime; // could use memcpy here!
uli.HighPart = ft.dwHighDateTime;

return uli.QuadPart/10000;
}

static void MillisToSystemTime(ULONGLONG millis, SYSTEMTIME *st)
{
UINT64 t = static_cast<UINT64>(-10000) * static_cast<UINT64>(millis);

FILETIME ft;
ft.dwLowDateTime = static_cast<DWORD(t & 0xFFFFFFFF);
ft.dwHighDateTime = static_cast<DWORD>(t >> 32);

::FileTimeToSystemTime(&ft, st);
}

void main()
{
SYSTEMTIME st, lt, st2, lt2;

::GetSystemTime(&st);
::GetLocalTime(&lt);

cout << "The system time is: " << st.wHour << ":" << st.wMinute << ":" << st.wSecond << endl;
cout << "The local time is: " << lt.wHour << ":" << lt.wMinute << ":" << lt.wSecond << endl;

FILETIME sft, lft;
::SystemTimeToFileTime(&st, &sft);
::SystemTimeToFileTime(&lt, &lft);

cout << "The system time in millis is: " << FileTimeToMillis(sft) << endl;
cout << "The local time in millis is: " << FileTimeToMillis(lft) << endl;

MillisToSystemTime(FileTimeToMillis(sft), &st2);
MillisToSystemTime(FileTimeToMillis(sft), &lt2);

cout << "The system time (post conversion) is: " << st2.wHour << ":" << st2.wMinute << ":" << st2.wSecond << endl;
cout << "The local time (post conversion) is: " << lt2.wHour << ":" << lt2.wMinute << ":" << lt2.wSecond << endl;
}

但我肯定没有得到预期的结果。相反,我得到:

The system time is: 15:5:2
The local time is: 10:5:2
The system time in millis is: 12984678302935
The local time in millis is: 12984660302935
The system time (post conversion) is: 52428:52428:52428
The local time (post conversion) is: 52428:52428:52428

有什么想法吗?请不要告诉我使用 Boost 或因为它对我不可用。

最佳答案

The system time (post conversion) is: 52428:52428:52428

当你得到奇怪的值时,总是先转换为十六进制。 52428 == 0xcccc。这是调试版本生成的代码用来初始化变量的值。所以你正在查看未初始化的内存。

下一个防御策略是从不忽略 Windows api 函数的返回值。使用 VERIFY() 宏,就像 MFC 中可用的宏一样。然后您会很容易地看到 FileTimeToSystemTime() 失败。

错误是-10000。

关于c++ - 如何从 ULONGLONG 毫秒创建 SYSTEMTIME 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11122647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com