且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测日期变化

更新时间:2023-02-26 14:53:44

没有Windows的回调服务会在午夜为您提供事件.因此,您将不得不定期询问当地时间(例如通过time()函数),并检查日期的更改.

There is no callback service of Windows that would give you an event at midnight. So you will have to ask regularly for the local time (e.g. by the time() function) and check for the change of the day number.

time_t t0 = time(0);
...

// detect midnight -- call regularly
time_t t1 = time(0);

int d0 = localtime (&t0)->tm_yday;
int d1 = localtime (&t1)->tm_yday;
t0 = t1;
if (d0 != d1)
{
   // detected midnight
   ...
}



localtime是一个相对耗时的功能.如果速度是该测试的主要问题,则您可能希望通过从time_t手动推导日数,以秒为单位减去时区偏移量,然后计算模量为86400(每天的秒数),从而优化该代码.但这需要小心,因为时区和DST偏移量可能会发生变化.



localtime is a relatively time consuming function. If speed is a major issue for that test, you might want to optimize that code by deriving the the day-number manually from time_t by subtracting the time-zone offset in seconds and calculating the modulus by 86400 (the number of seconds per day). But this requires some care as the the time-zone and DST offset might change.


通常,您需要自己注意过渡.如上建议的那样,以总价"方式进行操作,获取初始日期值,定期获取另一个日期值,并检查其是否已更改.检查频率或检查应用程序循环的频率将影响代码的性能.

另一种方法是创建一个线程,该线程确定何时发生下一个午夜"事件,然后触发/信号和事件/信号灯.或者,让该线程执行一天变化时所需的工作.

在Windows中,您可以像这样计算下一个午夜"
Well, in general, you will need to manage noticing the transition yourself. The "gross" way to do it as suggested above, get an initial date value, periodically get another date value and check to see if it changed. The frequency of how often you check or in what application loop you check will have an impact on your code''s performance.

The other way is to create a thread that determines when the next occurrance of "midnight" happens and then trigger / signal and event / semaphore. Or, have that thread do the work that is necessary when the day changes.

In Windows, you''d compute "next midnight" something like this
int midnight_sleep;
SYSTEMTIME cur_time;

// compute milliseconds until 1/2 second past midnight
GetLocalTime(&cur_time);
midnight_sleep = ((23 - cur_time.wHour) * 60 * 60 * 1000) +	
		 ((59 - cur_time.wMinute) * 60 * 1000) +
		 ((59 - cur_time.wSecond) * 1000) +
		 (1500 - cur_time.wMilliseconds);



当然,如果白天发生(或停止发生)夏令时或有人设置了系统时间,则上面的代码并不能完全正确.

实际上,如果有人更改了系统日期,您也不会立即检测到该日期.

因此,如果您关心日期本身何时确切更改",则需要执行强力方法,即经常将当前日期与以前保存的已知日期进行比较.而且,频率"可能每分钟或更短,取决于您对它的关心程度.



Of course the above code doesn''t get it exactly right if Daylight Savings Time happens (or stops happening) during the day or someone sets the system time.

In fact, if someone changes the system date, you wouldn''t detect that immediately either.

So, if you care about "Exactly when the Date itself changes", you need to do the brute force method of frequently comparing the current date to a previously saved known date. And "Frequently" can be every minute or finer, depending on how much you care about it.