SYSTEMTIME检查文件的LastWriteTime是昨天

时间:2015-03-09 11:58:40

标签: c++ winapi

我想检查一下LastWriteTimes与昨天系统日期相同的文件。我的问题是如何以SYSTEMTIME格式设置昨天的日期时间。 以下是我的代码。

    bool checkLastWriteTime(FILETIME ftLastWriteTime)
    {
        SYSTEMTIME stUTC, stLocal;
        // Convert the last-write time to local time.
        FileTimeToSystemTime(&ftLastWriteTime, &stUTC);
        SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);

        // Build a string showing the date and time.
        _tprintf(TEXT("%02d/%02d/%d  %02d:%02d\n"),
            stLocal.wMonth, stLocal.wDay, stLocal.wYear,
            stLocal.wHour, stLocal.wMinute);

        SYSTEMTIME localTime;
        GetLocalTime(&localTime);

      //
      //How to get the date of yesterday from localTime?
      //

        if (stLocal.wYear == localTime.wYear && stLocal.wMonth == localTime.wMonth && stLocal.wDay == localTime.wDay)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

2 个答案:

答案 0 :(得分:1)

"昨天"是范围。计算结束时很容易计算,发生在今天早上12点:

SYSTEMTIME now;
GetLocalTime(&now);
SYSTEMTIME stYesterdayEnd = { now.wYear, now.wMonth, now.wDayOfWeek, now.wDay };
FILETIME ftYesterdayEnd;
SystemTimeToFileTime(&stYesterdayEnd, &ftYesterdayEnd);

在此之前24小时开始。所以你需要从ftY yesterdayEnd中减去100纳秒的单位。使用FILETIME有点棘手,我们将使用LARGE_INTEGER来简化:

LARGE_INTEGER liYesterdayBeg = { ftYesterdayEnd.dwLowDateTime, ftYesterdayEnd.dwHighDateTime };
ULONGLONG oneday = 24ULL * 60 * 60 * 1000 * 1000 * 10;
liYesterdayBeg.QuadPart -= oneday;
FILETIME ftYesterdayBeg = { liYesterdayBeg.LowPart, liYesterdayBeg.HighPart };

现在你已经开始编写你的功能了:

bool wasWrittenYesterday(FILETIME ftLastWriteTime)
{
    // As above
    //...
    return ftLastWriteTime >= ftYesterdayBeg && ftLastWriteTime < ftYesterdayEnd
}

答案 1 :(得分:0)

您需要将SYSTEMTIME转换为FILETIME,然后减去日期并重新转换为SYSTEMTIME。

这样的事情:

FILETIME ft;
ULARGE_INTEGER uli;
__int64 oneDay;

GetLocalTime(&localTime);
SystemTimeToFileTime(&localTime, &ft);
memcpy(&uli, (ULARGE_INTEGER *)&ft, sizeof(ULARGE_INTEGER));

// get one day in 100ns parts
oneDay = (__int64)10 * (__int64)1000 * (__int64)1000;
oneDay *= (__int64)60 * (__int64)60 * (__int64)24;

// subtract one day 
uli.QuadPart -= oneDay;

FileTimeToSystemTime((LPFILETIME)&uli, &localTime);

运行此代码 localTime 包含 now 减去24小时。

另请参阅SYSTEMTIME参考

中的备注