Faced a task: there is some date, you need to calculate the difference in seconds between this date and the current system time. Ie I need to find out the number of seconds from the beginning of the era to the current moment, then to the date I need and subtract one from the other. The problem is that you need to take into account the transition to winter / summer time.

Example: By car, /etc/localtime refers to /usr/share/zoneinfo/Europe/Bucharest , where they have an hour ahead at 3:00. Suppose now is March 27, 2011, 02:10. I need to set the date to 5:10; if it was a normal day, the time difference would be three hours. But, in after 2:59:59 it will be immediately 4:00:00, so the difference between these dates is actually two hours.

I store the time in struct tm . There is a tm_isdst field that seems to be responsible for whether the translation of arrows applies to a given date. If in my example, put tm_isdst =1 , then localtime_r will tm_isdst =1 correct result. But the trick is that for an arbitrarily chosen date I can’t say whether the translation of the arrows applies to it :(

What to do?

    3 answers 3

    Try using the mktime () call. In the tm structure passed to it, set the tm_isdst variable to -1. Then mktime will determine for itself whether daylight saving time was effective or not.

    • thanks, it turned out exactly what was needed - beardog

    Those. it turns out that on the day of daylight saving time you will have 25 hours in a day! This is nonsense.

    The difference in time in hours does not depend on the transition to summer and winter time. Moreover, now there is no transition in our country.

    • 23 hours But in general it is true: if there is a transition to winter time between two dates, you need to add one hour; if the summer - take away. If both transitions - they compensate each other and the result will be correct. There are still a lot of countries in the world where presidents do not think about their people :) - beardog
    • dear @beardog let's not talk about politics though xD - Zowie

    If you take time in the unix timestamp, then you do not need to read the difference for daylight saving time.