[ntp:hackers] Fixing caljulian to survive timestamp wraparounds

Terje Mathisen terje.mathisen at hda.hydro.com
Thu Nov 20 09:26:50 PST 2003


Harlan have asked me to fix this potential problem (probably due to all 
my date-related posts), and that's fine, I've written two different 
versions of an algorithm that would fix the problem.

However, working from the principle that the most bugfree and easiest to 
maintain code is the one you don't have to write at all, I want to make 
a suggestion:

a) All systems that want to survive the unix wraparound in 2038 must fix 
their C libraries so that time_t has more than 32 bits before this 
happens, right?

b) I assume that all timestamps caljulian() is asked to convert will be 
for times relatively close to the current UTC time, right?

c) Since a 32-bit ntp timestamp covers a 136 year period, the best we 
can ever do is to determine which epoch a given timestamp should belong 
to, i.e. if the time is further away than 68 years, there's no way to 
guess this.

(One possible exception might be made for the special timestamp of 0:0, 
which could be assumed to always refer to the NTP 1900-01-01 epoch?)

Anyway, given that at least (a) and (b) is true, the best way to convert 
an ntp timestamp to a calendar date would be to first convert the 
ntptime to time_t, then adjust the base by 70 years (1970 - 1900 epoch 
bases), and check that the offset between this time and the current time 
will fit in a 32-bit signed int.

If not, start a loop adding 2^32 seconds each time until the difference 
is small enough.

(On a system with 32-bit time_t this test will never be true, and the 
loop cannot be entered!)

Finally, the gmtime() library function can do the actual conversion.

gmtime() is standard on all platforms now, right?

Comments before I try to submit this fix via bk?

Terje
-- 
- <Terje.Mathisen at hda.hydro.com>
"almost all programming can be viewed as an exercise in caching"





More information about the hackers mailing list