All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
1 local gettime = require "luatz.gettime".gettime
3 local tz_info_methods = { }
5 __index = tz_info_methods ;
11 local function _find_current ( tzinfo , target , i , j )
12 if i >= j then return j end
14 local half = math.ceil ( (j+i) / 2 )
16 if target >= tzinfo [ half ].transition_time then
17 return _find_current ( tzinfo , target , half , j )
19 return _find_current ( tzinfo , target , i , half-1 )
23 local function find_current_local ( tzinfo , ts_local )
24 -- Find two best possibilities by searching back and forward a day (assumes transition is never by more than 24 hours)
25 local tz_first = _find_current ( tzinfo , ts_local-86400 , 0 , #tzinfo )
26 local tz_last = _find_current ( tzinfo , ts_local+86400 , 0 , #tzinfo )
28 local n_candidates = tz_last - tz_first + 1
30 if n_candidates == 1 then
32 elseif n_candidates == 2 then
33 local tz_first_ob = tzinfo [ tz_first ]
34 local tz_last_ob = tzinfo [ tz_last ]
36 local first_gmtoffset = tz_first_ob.info.gmtoff
37 local last_gmtoffset = tz_last_ob .info.gmtoff
39 local t_start = tz_last_ob.transition_time + first_gmtoffset
40 local t_end = tz_last_ob.transition_time + last_gmtoffset
42 -- If timestamp is before start or after end
43 if ts_local < t_start then
45 elseif ts_local > t_end then
49 -- If we get this far, the local time is ambiguous
50 return tz_first , tz_last
52 error ( "Too many transitions in a 2 day period" )
56 function tz_info_methods:find_current ( current )
57 return self [ _find_current ( self , current , 0 , #self ) ].info
60 function tz_info_methods:localise ( utc_ts )
61 utc_ts = utc_ts or gettime ( )
62 return utc_ts + self:find_current ( utc_ts ).gmtoff
64 tz_info_methods.localize = tz_info_methods.localise
66 function tz_info_methods:utctime ( ts_local )
67 local tz1 , tz2 = find_current_local ( self , ts_local )
68 tz1 = self [ tz1 ].info
70 return ts_local - tz1.gmtoff
71 else -- Local time is ambiguous
72 tz2 = self [ tz2 ].info
74 return ts_local - tz2.gmtoff , ts_local - tz2.gmtoff
79 tz_info_mt = tz_info_mt ;
80 tt_info_mt = tt_info_mt ;