30 days Difference on SYSTEMTIME

2019-06-10 13:21发布

问题:

I am willing to ask if anyone has some good algorithm (or ways) to check if two SYSTEMTIME variable has a diff of 30 days or longer?

Thank you

回答1:

I would convert them to FileTime and substract one from another.
The difference should be more than 30*24*60*60*10^7.



回答2:

As the MSDN page on SYSTEMTIME says,

It is not recommended that you add and subtract values from the SYSTEMTIME structure to obtain relative times. Instead, you should

  • Convert the SYSTEMTIME structure to a FILETIME structure.
  • Copy the resulting FILETIME structure to a ULARGE_INTEGER structure.
  • Use normal 64-bit arithmetic on the ULARGE_INTEGER value.
SYSTEMTIME st1, st2;
/* ... */
FILETIME ft1, ft2;
ULARGE_INTEGER t1, t2;
ULONGLONG diff;
SystemTimeToFileTime(&st1, &ft1);
SystemTimeToFileTime(&st2, &ft2);
memcpy(&t1, &ft1, sizeof(t1));
memcpy(&t2, &ft2, sizeof(t1));
diff = (t1.QuadPart<t2.QuadPart)?(t2.QuadPart-t1.QuadPart):(t1.QuadPart-t2.QuadPart);
if(diff > (30*24*60*60)*(ULONGLONG)10000000)
{
    ...
}

(error handling on calls to SystemTimeToFileTime omitted for brevity)

About the (30*24*60*60)*(ULONGLONG)10000000: 30*24*60*60 is the number of seconds in 30 days; 10000000 is the number of FILETIME "ticks" in a second (each FILETIME tick is 100 ns=10^2*10^-9 s=10^-7 s). The cast to one of the operands in the multiplication is to avoid overflowing regular ints (the default when performing operations between integer literals that fit the range of an int).



回答3:

microsoft advises to

  • convert the SYSTEMTIME structure to a FILETIME structure (64-bit value, representing the number of 100-nanosecond intervals since January 1, 1601 (UTC))
  • copy the results to a ULARGE_INTEGER and perform normal integer arithmetic on top of that

useful could be:

  • SystemTimeToFileTime(...)