0

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

Allan Jiang
  • 11,063
  • 27
  • 104
  • 165
  • 3
    I'd probably convert both to a FILETIME and compare them that way. You would use the SystemTimeToFileTime funtion to do it, and then just do the math. – Retired Ninja Jun 14 '12 at 23:53

3 Answers3

7

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).

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
6

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

GSerg
  • 76,472
  • 17
  • 159
  • 346
  • Thank you, but can you please take a second to explain the `30*24*60*60*10^7` number a little bit? Just want to make sure no one gets any mistake on it. – Allan Jiang Jun 14 '12 at 23:58
  • 1
    @AllanJiang This is the number of 100-nanosecond intervals in 30 days. [`FileTime`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx) has 100-nanosecond resolution, as you can find out by clicking the link. – GSerg Jun 15 '12 at 00:00
  • 2
    I would be very careful about using ^ in C based languages as it's a logical xor, rather than an exponent operation! – Owl Jan 23 '17 at 13:15
  • 1
    This ignores leap seconds. – Lightness Races in Orbit Aug 30 '18 at 13:27
0

microsoft advises to

useful could be:

xmoex
  • 2,602
  • 22
  • 36