Module:Time/sandbox: Difference between revisions

Content deleted Content added
No edit summary
No edit summary
 
(98 intermediate revisions by 5 users not shown)
Line 1:
require ('Module:No globalsstrict')
local yesno = require('Module:Yesno')
local getArgs = require ('Module:Arguments').getArgs
local data = mw.loadData ('Module:Time/data' .. (mw.getCurrentFrame():getTitle():match ('/sandbox') or '')); -- load the data module
local cfg = data.cfg; -- for internationalization
 
local tz = {}; -- holds local copy of the specified timezone table from tz_data{}
 
 
Line 12 ⟶ 15:
 
local function is_set( var )
return not (varnil == nilvar or var'' == ''var);
end
 
 
--[[--------------------------< S U B S T I T U T E >----------------------------------------------------------
 
Populates numbered arguments in a message string using an argument table.
 
]]
 
local function substitute (msg, args_t)
return args_t and mw.message.newRawMessage (msg, args_t):plain() or msg;
end
 
 
--[[--------------------------< E R R O R _ M S G >------------------------------------------------------------
 
create an error message
<args_t> is a sequence where [1] is template name and [2] is substituted error message
]]
 
local function error_msg (args_t)
return substitute (cfg.err_msg, args_t);
end
 
Line 30 ⟶ 55:
local function decode_dst_event (dst_event_string)
local ord, day, month;
local ordinals = {['1st'] = 1, ['first'] = 1, ['2nd'] = 2, ['second'] = 2, ['3rd'] = 3, ['third'] = 3, ['4th'] = 4, ['fourth'] = 4, ['5th'] = 5, ['fifth'] = 5, ['last'] = -1};
local days = {['sunday'] = 0, ['monday'] = 1, ['tuesday'] = 2, ['wednesday'] = 3, ['thursday'] = 4, ['friday'] = 5, ['saturday'] = 6};
local months = {['january'] = 1, ['february'] = 2, ['march'] = 3, ['april'] = 4, ['may'] = 5, ['june'] = 6,
['july'] = 7, ['august'] = 8, ['september'] = 9, ['october'] = 10, ['november'] = 11, ['december'] = 12};
dst_event_string = dst_event_string:lower(); -- force the string to lower case because that is how the tables above are indexed
Line 43 ⟶ 63:
end
return cfg.ordinals[ord], cfg.days[day], cfg.months[month];
end
 
Line 102 ⟶ 122:
if -1 == ord then -- j = t + 7×(n + 1) - (wt - w) mod 7 -- if event occurs on the last day-name of the month ('last Sunday of October')
days_in_month = get_days_in_month (year, month);
last_day_of_dst_month_num = os.date ('%w', os.time ({['year']=year, ['month']=month, ['day']=days_in_month}));
return month, days_in_month + 7*(ord + 1) - ((last_day_of_dst_month_num - weekday_num) % 7);
else -- j = 7×n - 6 + (w - w1) mod 7
Line 129 ⟶ 149:
return sign * ((hours * 3600) + (minutes * 60));
else
return nil; -- we require that all timezone tabletables have what appears to be a valid offset
end
end
Line 206 ⟶ 226:
--[[--------------------------< G E T _ T E S T _ T I M E >----------------------------------------------------
 
decode ISO formatted date/time into a table suitable for os.time(). ForFallback testing,to this{{Timestamp}} time is utc just as isformat.
For testing, this time is UTC just as is returned by the os.time() function.
 
]]
Line 214 ⟶ 234:
local year, month, day, hour, minute, second;
 
year, month, day, hour, minute, second = iso_date:match ('(%d%d%d%d)\%-(%d%d)\%-(%d%d)T(%d%d):(%d%d):(%d%d)');
if not year then
year, month, day, hour, minute, second = iso_date:match ('^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)$');
return nil; -- test time did not match the specified pattern
if not year then
return nil; -- test time did not match the specified patterns
end
end
return {['year'] = year, ['month'] = month, ['day'] = day, ['hour'] = hour, ['min'] = minute, ['sec'] = second};
Line 223 ⟶ 246:
--[[----------------------< G E T _ F U L L _ U T C _ O F F S E T >-----------------------------------------------
 
Creates a standard UTC offset from variousnumerical inputs, for function time to convert to a table. Expected inputs shall have the form:
<sign><hour><separator><portion>
where:
<sign> – optional; one of the characters: '+', '-' (hyphen), '±', '−' (minus); defaults to '+'
<hour> - one or two digits
<separator> - one of the characters '.' or ':'; required when <portion> is included; ignored else
<portion> - optional; one or two digits when <separator> is '.'; two digits else
 
returns correct utc offset string when input has a correct form; else returns the unmodified input
 
]]
 
local function get_full_utc_offset (utc_offset, format) -- for below [] = required, () = not required
local minoffh, m, sep, sign;
local houroff;
local sign;
local no_sign;
local minzero;
local hourzero;
local patterns = {
if mw.ustring.match (utc_offset, 'u?t?c?[%+%-±−]?%d+%.%d+') == utc_offset then -- if rendering for a utc offset with (utc)(sign)(number)[number][.](number)[number]
'^([%+%-±−]?)(%d%d?)(%.)(%d%d?)$', -- one or two fractional hour digits
houroff = mw.ustring.match (utc_offset, '%d+')
'^([%+%-±−]?)(%d%d?)(:)(%d%d)$', -- two minute digits
no_sign = mw.ustring.match (utc_offset, '%d+%.%d+')
'^([%+%-±−]?)(%d%d?)[%.:]?$', -- hours only; ignore trailing separator
minoff = ((no_sign*100)-(houroff*100))*0.6
}
sign = mw.ustring.match (utc_offset,'[%+%-±−]?')
if is_set(sign) == false then
for _, pattern in ipairs(patterns) do -- loop through the patterns
sign = '+'
sign, h, sep, m = mw.ustring.match (utc_offset, pattern);
end
if h then
if hourzero == mw.ustring.match (hourzero,'%d') < 10 then
break; -- if h is set then pattern matched
hourzero = '0'
else
hourzero = ''
end
if minzero == mw.ustring.match (minzero,'%d') < 10 then
minzero = '0'
else
minzero = ''
end
utc_offset = table.concat ({'utc',sign,hourzero,houroff,':',minzero,minoff})
if is_set(format) == false then
format = 'dmy'
end
elseif mw.ustring.match (utc_offset, 'u?t?c?[%+%-±−]?%d+') == utc_offset then -- if rendering for a utc offset with (utc)(sign)(number)[number]
sign = mw.ustring.match (utc_offset, '[%+%-±−]?')
utc_offset = mw.ustring.match (utc_offset, '%d+')
if is_set(sign) == false then
sign = '+'
end
if utc_offset == mw.ustring.match (utc_offset, '%d') then
utc_offset = table.concat ({'utc',sign,0,utc_offset,':00'})
else
utc_offset = table.concat ({'utc',sign,utc_offset,':00'})
end
if is_set(format) == false then
format = 'dmy'
end
elseif mw.ustring.match (utc_offset,'u?t?c?[%+%-±−]?%d+:%d%d') == utc_offset then -- if rendering for a utc offset with (utc)(sign)(number)[number][:][number][number]
sign = mw.ustring.match (utc_offset, '[%+%-±−]?')
utc_offset = mw.ustring.match (utc_offset, '%d+:%d%d')
if is_set(sign) == false then
sign = '+'
end
if utc_offset == mw.ustring.match (utc_offset, '%d:%d%d') then
utc_offset = table.concat ({'utc',sign,0,utc_offset})
else
utc_offset = table.concat ({'utc',sign,utc_offset})
end
if is_set(format) == false then
format = 'dmy'
end
end
 
if not h then
return utc_offset; -- did not match a pattern
end
sign = ('' == sign) and '+' or sign; -- sign character is required; set to '+' if not specified
return utc_offset, format
 
m = ('.' == sep) and ((sep .. m) * 60) or m or 0; -- fractional h to m
 
return string.format ('utc%s%02d:%02d', sign, h, m);
end
 
 
--[[--------------------------< T A B L E _ L E N >------------------------------------------------------------
 
return number of elements in table
 
]]
 
local function table_len (tbl)
local count = 0;
for _ in pairs (tbl) do
count = count + 1;
end
return count;
end
 
 
--[[--------------------------< F I R S T _ S E T >------------------------------------------------------------
 
scans through a list of parameter names that are aliases of each other and returns the value assigned to the
first args[alias] that has a set value; nil else. scan direction is right-to-left (top-to-bottom)
 
]]
 
local function first_set (list, args)
local i = 1;
local count = table_len (list); -- get count of items in list
while i <= count do -- loop through all items in list
if is_set( args[list[i]] ) then -- if parameter name in list is set in args
return args[list[i]]; -- return the value assigned to the args parameter
end
i = i + 1; -- point to next
end
end
 
 
--[=[-------------------------< T I M E >----------------------------------------------------------------------
 
Line 307 ⟶ 337:
 
Timezone abbreviations can be found here: [[List_of_time_zone_abbreviations]]
 
For custom date format parameters |df-cust=, |df-cust-a=, |df-cust-p= use codes
described here: [[:mw:Help:Extension:ParserFunctions##time]]
 
]=]
Line 318 ⟶ 351:
local utc_offset;
local invert; -- true when southern hemisphere
local dfDF; -- date format flag; the |df= parameter
local is_dst_tz;
 
local timeonlytz_aliases = 'yes' == argsdata.timeonlytz_aliases; -- booleanget the aliases table
local dateonlytz_data = 'yes' == argsdata.dateonlytz_data; -- booleanget the tz data table
local hide_refresh = 'yes' == args['hide-refresh']; -- boolean
local hide_tz = 'yes' == args['hide-tz']; -- boolean
local unlink_tz = 'yes' == args['unlink-tz']; -- boolean
 
local Timeonly = yesno(first_set (cfg.aliases['timeonly'], args)); -- boolean
if timeonly and dateonly then -- invalid condition when both are set
local Dateonly = yesno(first_set (cfg.aliases['dateonly'], args)); -- boolean
timeonly, dateonly = false;
if Timeonly and Dateonly then -- invalid condition when both are set
Timeonly, Dateonly = false;
end
local Hide_refresh = yesno(first_set (cfg.aliases['hide-refresh'], args)); -- boolean
local tz_data = table.concat ({'Module:Time/data', frame:getTitle():find('sandbox', 1, true) and '/sandbox' or ''}); -- make a data module name; sandbox or live
local Hide_tz = yesno(first_set (cfg.aliases['hide-tz'], args)); -- boolean
tz_data = mw.loadData (tz_data).tz_data; -- load the data table
local Unlink_tz = yesno(first_set (cfg.aliases['unlink-tz'], args)); -- boolean
local DST = first_set (cfg.aliases['dst'], args) or true; -- string 'always' or boolean
local Lang = first_set (cfg.aliases['lang'], args); -- to render in a language other than the local wiki's language
local DF_cust = first_set (cfg.aliases['df-cust'], args); -- custom date/time formats
local DF_cust_a = first_set (cfg.aliases['df-cust-a'], args); -- for am/pm sensitive formats
local DF_cust_p = first_set (cfg.aliases['df-cust-p'], args);
 
if not ((DF_cust_a and DF_cust_p) or -- DF_cust_a xor DF_cust_p
(not DF_cust_a and not DF_cust_p))then
return error_msg ({'Time', cfg.err_text['bad_df_pair']}); -- both are required
end
 
if args[1] then
args[1] = get_full_utc_offset (args[1]):lower(); -- make lower case because tz table member indexes are lower case
else
args[1] = 'utc'; -- default to utc
end
args[1], args[2] = get_full_utc_offset (args[1],args[2])
if mw.ustring.match (args[1], '%.%d+') then
return '<span style="font-size:100%" class="error">{{time}} – input produces invalid minute offset ([[Template:Time#Error messages|help]])</span>';
end
 
if mw.ustring.match (args[1], 'utc[%+%-±−]?%d%d:%d%d') then -- if rendering time for a UTC offset timezone
tz.abbr = args[1]:upper():gsub('%-', '−'); -- set the link label to upper case and replace hyphen with a minus character (U+2212)
tz.article = tz.abbr; -- article title same as abbreviation
tz.utc_offset = mw.ustring.match (args[1], 'utc([%+%-±−]?%d%d:%d%d)'):gsub('−', '%-'); -- extract the offset value; replace minus character with hyphen
local s, t = mw.ustring.match (tz.utc_offset, '(±)(%d%d:%d%d)'); -- ± only valid for offset 00:00
if s and '00:00' ~= t then
return error_msg ({'Time', cfg.err_text['bad_sign']});
end
tz.df = 'iso';
args[1] = 'utc_offsets'; -- spoof to show that we recognize this timezone
else
tz = tz_aliases[args[1]] and tz_data[tz_aliases[args[1]]] or tz_data[args[1]]; -- make a local copy of the timezone table from tz_data{}
tz = tz_data[args[1]];
if not tz then
if not is_set(tz) then -- make a local copy of the timezone table from tz_data{}
return '<spanerror_msg style="font-size:100%" class="error">({{time}}'Time', – unknown timezonesubstitute (cfg.err_text['unknown_tz'], args[Template:Time#Error messages|help]1])</span>'}); -- if the timezone given isn't in module:time/data(/sandbox)
end -- make a local copy of the timezone table from tz_data{}
if is_set (tz.tz) then -- if tz table has a tz value
tz = tz_data[tz.tz]; -- redo tz table for proper tz abbrev.
end
end
 
dfDF = argsfirst_set (cfg.aliases['df'], args) or args[2] or tz.df or 'mdy'cfg.default_df; -- template |df= overrides typical df from tz properties TODO: error check these values?
DF = DF:lower(); -- normalize to lower case
if is_set (df) then
if not cfg.df_vals[DF] then
df = df:lower(); -- lower case because we will compare to lower case values later
return error_msg ({'Time', substitute (cfg.err_text['bad_format'], DF)});
end
 
Line 370 ⟶ 412:
local test_time = get_test_time (args._TEST_TIME_);
if not test_time then
return error_msg ({'Time', cfg.err_text['test_time']});
return '<span style="font-size:100%" class="error">{{time}} – malformed or incomplete _TEST_TIME_ ([[Template:Time#Error messages|help]])</span>';
end
 
-- utc_timestamp = os.time(get_test_time (args._TEST_TIME_));
utc_timestamp = os.time(test_time);
else
Line 381 ⟶ 422:
timestamp = utc_timestamp + utc_offset; -- make local time timestamp
 
if 'noalways' == args.dstDST then -- forif timezonesneeded thatto DOalways observedisplay dst but for this ___location ...time
tz_abbrtimestamp = tz.abbrtimestamp + 3600; -- ...add dsta ishour notfor observed (|dst=no) show time as standard time
elseif 'always' == args.dst then -- if needed to always display dts time
timestamp = timestamp + 3600; -- adds a hour for dst
tz_abbr = tz.dst_abbr; -- dst abbreviation
elseif not yesno(DST) then -- for timezones that DO observe dst but for this ___location ...
tz_abbr = tz.abbr; -- ... dst is not observed (|dst=no) show time as standard time
else
if is_set (tz.dst_begins) and is_set (tz.dst_ends) and is_set (tz.dst_time) then -- make sure we have all of the parts
Line 391 ⟶ 432:
 
if nil == dst_begin_ts or nil == dst_end_ts then
return error_msg ({'Time', cfg.err_text['bad_dst']});
return '<span style="font-size:100%" class="error">{{time}} – error calculating dst timestamps ([[Template:Time#Error messages|help]])</span>';
end
Line 410 ⟶ 451:
end
elseif is_set (tz.dst_begins) or is_set (tz.dst_ends) or is_set (tz.dst_time) then -- if some but not all not all parts then emit error message
return error_msg ({'Time', substitute (cfg.err_text['bad_def'], args_t[1]:upper())});
return table.concat ({'<span style="font-size:100%" class="error">{{time}} – incomplete definition for ', args[1]:upper(), ' ([[Template:Time#Error messages|help]])</span>'});
else
tz_abbr = tz.abbr; -- dst not observed for this timezone
Line 416 ⟶ 457:
end
if dateonlyDateonly then
if 'iso' == dfDF then -- |df=iso
dfDF = 'iso_date';
elseif dfDF:find ('^dmy') or 'y' == dfDF then -- |df=dmy, |df=dmy12, |df=dmy24, |df=y
dfDF = 'dmy_date';
else
dfDF = 'mdy_date'; -- default
end
 
elseif timeonlyTimeonly or dfDF:match ('^%d+$') then -- time only of |df= is just digits
dfDF = table.concat ({'t', dfDF:match ('%l*(12)') or '24'}); -- |df=12, |df=24, |df=dmy12, |df=dmy24, |df=mdy12, |df=mdy24; default to t24
elseif 'y' == dfDF or 'dmy24' == dfDF then
dfDF = 'dmy';
 
elseif 'mdy24' == dfDF then
dfDF = 'mdy';
end
local format = {dformat;
if is_set (DF_cust) then
t12 = '%l:%M %p', -- time only
dformat=DF_cust;
t24 = '%R',
elseif is_set (DF_cust_a) then -- custom format is am/pm sensitive?
iso_dateif 'am' == os.date ('%FP', timestamp) then -- dateif current time is onlyam
dformat = DF_cust_a; -- use custom am format
dmy_date = '%e %B %Y',
else
mdy_date = '%B %e, %Y',
dformat = DF_cust_p; -- use custom pm format
end
dmy12 = '%l:%M %p, %e %B %Y', -- 12hr time and date
mdy12 = '%l:%M %p, %B %e, %Y',
dmy = '%R, %e %B %Y', -- 24hr time and date
mdy = '%R, %B %e, %Y',
iso = '%FT%R'
}
if format[df] then
time_string = mw.text.trim (os.date (format[df], timestamp));
else
dformat = cfg.format[DF]; -- use format from tables or from |df=
return table.concat ({'<span style="font-size:100%" class="error">{{time}} – invalid date format ', df, ' ([[Template:Time#Error messages|help]])</span>'});
end
 
time_string = frame:callParserFunction ({name='#time', args={dformat, '@'..timestamp, Lang}});
if Lang then
time_string = table.concat ({ -- bidirectional isolation of non-local language; yeah, rather brute force but simple
'<bdi lang="', -- start of opening bdi tag
Lang, -- insert rendered language code
'">', -- end of opening tag
time_string, -- insert the time string
'</bdi>' -- and close the tag
});
end
 
if not is_set (tz.article) then -- if some but not all not all parts then emit error message
return error_msg ({'Time', substitute (cfg.err_text['bad_def'], args_t[1]:upper())});
return table.concat ({'<span style="font-size:100%" class="error">{{time}} – incomplete definition for ', args[1]:upper(), ' ([[Template:Time#Error messages|help]])</span>'});
end
local refresh_link = (hide_refreshHide_refresh and '') or
table.concat ({
' <span class="plainlinks" style="font-size:85%;">[[', -- open span
mw.title.getCurrentTitle():fullUrl({action = 'purge'}), -- add the a refresh link url
' ',
' refresh]]</span>', -- close the span
cfg['refresh-label'], -- add the label
']]</span>', -- close the span
});
 
local tz_tag = (hide_tzHide_tz and '') or
((unlink_tzUnlink_tz and table.concat ({' ', tz_abbr})) or -- unlinked
table.concat ({' [[', tz.article, '|', tz_abbr, ']]'})); -- linked
return table.concat ({time_string, tz_tag, refresh_link});
 
end
 
 
--[[--------------------------< U T C _ O F F S E T >----------------------------------------------------------
 
implements {{UTC offset}}
 
mimics templates {{Time/GMT offset}}, {{Time/EST offset}}, etc.
 
{{#invoke:Time|utc_offset|<tz>}} – for a stand-alone invoke
{{#invoke:Time|utc_offset}} – for an invoke in a template (<tz> is first positional parameter in the template call)
 
where <tz> is a timezone abbreviation known to Module:Time/data
 
returns a UTC offset string suitable for use with the {{#time:}} parser function:
{{#time:H:i | {{#invoke:Time|utc_offset|MST}} }}
{{#time:H:i | {{UTC_offset|MST}} }}
 
]]
 
local function utc_offset (frame)
local function apply_dst_ajdust (offset) -- local function to adjust standard time to daylight time; called when adjustment is needed
local hours, minutes = offset:match ('^(%-?%d%d):(%d%d)'); -- extract signed hours and minutes from specified offset
return string.format ('%s:%s', tonumber (hours) + 1, minutes); -- return optional sign hh:mm string
end
 
local args_t = getArgs (frame); -- fetch arguments; only {{{1}}}, timesone specifier is used
 
if not args_t[1] then -- no timezone specifier
return error_msg ({'UTC offset', cfg.err_text['missing_tz']}); -- abandon with error message
end
 
local timezone = args_t[1]:lower(); -- lowercase for indexing into tz data tables
timezone = data.tz_aliases[timezone] or timezone; -- if <timezone> is an alias, map to its canonical value
 
if not data.tz_data[timezone] then -- timezone specifier not known
return error_msg ({'UTC offset', substitute (cfg.err_text['unknown_tz'], {timezone})}); -- abandon with error message
end
 
tz = data.tz_aliases[timezone] and data.tz_data[data.tz_aliases[timezone]] or data.tz_data[timezone]; -- fetch a copy of this timezone's data; <tz> is a page-global table used by functions called from this function
local utc_timestamp = os.time (); -- get current server time (UTC) in seconds; used to determine when dst adjustment should be applied
 
local timestamp = utc_timestamp + get_utc_offset (); -- make local time timestamp (in seconds)
local utc_offset;
 
local DST = first_set (cfg.aliases['dst'], args_t) or true; -- string 'always' or boolean
if 'always' == DST then -- if needed to always display dst time
utc_offset = apply_dst_ajdust (tz.utc_offset); -- return dst-adjusted timezone-offset from utc
elseif not yesno (DST) then -- for timezones that DO observe dst but for this ___location ...
utc_offset = tz.utc_offset; -- ... dst is not observed (|dst=no) show time as standard time
else
if is_set (tz.dst_begins) and is_set (tz.dst_ends) and is_set (tz.dst_time) then -- make sure we have all of the parts
local dst_begin_ts, dst_end_ts, invert = make_dst_timestamps (timestamp); -- get begin and end dst timestamps and <invert> flag
if nil == dst_begin_ts or nil == dst_end_ts then -- if either of these are nil
return error_msg ({'UTC offset', cfg.err_text['bad_dst']}); -- abandon with error message
end
if invert then -- southern hemisphere; use beginning and ending of standard time in the comparison
if utc_timestamp >= dst_end_ts and utc_timestamp < dst_begin_ts then -- is current date time standard time?
utc_offset = tz.utc_offset; -- return timezone-offset from utc
else
utc_offset = apply_dst_ajdust (tz.utc_offset); -- return dst-adjusted timezone-offset from utc
end
else -- northern hemisphere
if utc_timestamp >= dst_begin_ts and utc_timestamp < dst_end_ts then -- is current date time daylight time?
utc_offset = apply_dst_ajdust (tz.utc_offset); -- return dst-adjusted timezone-offset from utc
else
utc_offset = tz.utc_offset; -- return timezone-offset from utc
end
end
elseif is_set (tz.dst_begins) or is_set (tz.dst_ends) or is_set (tz.dst_time) then -- if some but not all not all parts then emit error message
return error_msg ({'UTC offset', substitute (cfg.err_text['bad_def'], args_t[1]:upper())});
else -- timezone does not use dst
utc_offset = tz.utc_offset; -- return timezone-offset from utc
end
end
local sign, hours, minutes = utc_offset:match ('^([%-%+]?)(%d%d?):(%d%d)')
if '' == sign then
sign = '+';
end
if 0 ~= tonumber (minutes) then
return string.format ('%s%s %s %s%s minutes', sign, tonumber(hours), ('1' == hours) and 'hour' or 'hours', sign, tonumber(minutes));
else
return string.format ('%s%s %s', sign, tonumber(hours), ('1' == hours) and 'hour' or 'hours');
end
end
 
Line 479 ⟶ 615:
]]
 
return {
time = time},
utc_offset = utc_offset,
}