ms = 0
end
local m = math.floor(ms)
local s = (ms - m) * 60
if p > 0.008 then -- precision is > 1/2 a minute
if s > 30 then m = m +1 end
s = 0
elseif p > 0.00014 then -- precision is > 1/2 a second
s = math.floor(s + 0.5)
elseif p > 0.000014 then -- precision is > 1/20 second
s = math.floor(10 * s + 0.5) / 10
elseif p > 0.0000014 then -- precision is > 1/200 second
s = math.floor(100 * s + 0.5) / 100
else -- cap it at 3 dec places for now
s = math.floor(1000 * s + 0.5) / 1000
end
return d, m, s
end  
---
-- decimalPrecision takes a decimal (x) with precision (p)
-- and returns x rounded approximately to the given precision
-- precision should be between 1 and 1e-6, preferably a power of 10.
---
-- Dependencies:
---
local decimalPrecision = function(x, p)
local s = 1
if x < 0 then
x = -x
s = -1
end
-- if p is not supplied, pick an arbitrary precision
if not tonumber(p) then p = 1e-4
elseif p > 1 then p = 1
elseif p < 1e-6 then p = 1e-6
else p = 10 ^ math.floor(math.log10(p))
end
x = math.floor(x / p + 0.5) * p * s
-- if it's integral, cast to an integer:
if x == math.floor(x) then x = math.floor(x) end
-- if it's less than 1e-4, it will be in exponent form, so return a string with 6dp
-- 9e-5 becomes 0.000090
if math.abs(x) < 1e-4 then x = string.format("%f", x) end
return x
end  
---
-- formatDate takes a datetime of the usual format from mw.wikibase.entity:formatPropertyValues
-- like "1 August 30 BCE" as parameter 1
-- and formats it according to the df (date format) and bc parameters
-- df = ["dmy" / "mdy" / "y"] default will be "dmy"
-- bc = ["BC" / "BCE"] default will be "BCE"
---
-- Dependencies:
---
local format_Date = function(datetime, dateformat, bc)
local datetime = datetime or "1 August 30 BCE" -- in case of nil value
-- chop off multiple vales and/or any hours, mins, etc.
-- keep anything before punctuation - we just want a single date:
local dateval = string.match( datetime, "[%w ]+")  
local dateformat = string.lower(dateformat or "dmy") -- default to dmy  
local bc = string.upper(bc or "") -- can't use nil for bc
-- we only want to accept two possibilities: BC or default to BCE
if bc == "BC" then
bc = "&nbsp;" .. i18n["BC"] -- prepend a non-breaking space.
else
bc = "&nbsp;" .. i18n["BCE"]
end  
local postchrist = true -- start by assuming no BCE
local dateparts = {}
for word in string.gmatch(dateval, "%w+") do
if word == "BCE" or word == "BC" then -- *** internationalise later ***
postchrist = false
else
-- we'll keep the parts that are not 'BCE' in a table
dateparts[#dateparts + 1] = word
end
end
if postchrist then bc = "" end -- set AD dates to no suffix *** internationalise later ***  
local sep = "&nbsp;" -- separator is nbsp
local fdate = table.concat(dateparts, sep) -- set formatted date to same order as input  
-- if we have day month year, check dateformat
if #dateparts == 3 then
if dateformat == "y" then
fdate = dateparts[3]
elseif dateformat == "mdy" then
fdate = dateparts[2] .. sep .. dateparts[1] .. "," .. sep .. dateparts[3]
end
elseif #dateparts == 2 and dateformat == "y" then
fdate = dateparts[2]
end  
return fdate .. bc
end  
---
-- dateFormat is the handler for properties that are of type "time"
-- It takes timestamp, precision (6 to 11 per mediawiki), dateformat (y/dmy/mdy), BC format (BC/BCE),
-- a plaindate switch (yes/no/adj) to en/disable "sourcing circumstances"/use adjectival form,
-- any qualifiers for the property, the language, and any adjective to use like 'before'.
-- It passes the date through the "complex date" function
-- and returns a string with the internatonalised date formatted according to preferences.
---
-- Dependencies: findLang; cdate; dp[]
---
local dateFormat = function(timestamp, dprec, df, bcf, pd, qualifiers, lang, adj, model)
-- output formatting according to preferences (y/dmy/mdy/ymd)
df = (df or ""):lower
-- if ymd is required, return the part of the timestamp in YYYY-MM-DD form
-- but apply Year zero#Astronomers fix: 1 BC = 0000; 2 BC = -0001; etc.
if df == "ymd" then
if timestamp:sub(1,1) == "+" then
return timestamp:sub(2,11)
else
local yr = tonumber(timestamp:sub(2,5)) - 1
yr = ("000" .. yr):sub(-4)
if yr ~= "0000" then yr = "-" .. yr end
return yr .. timestamp:sub(6,11)
end
end
-- A year can be stored like this: "+1872-00-00T00:00:00Z",
-- which is processed here as if it were the day before "+1872-01-01T00:00:00Z",
-- and that's the last day of 1871, so the year is wrong.
-- So fix the month 0, day 0 timestamp to become 1 January instead:
timestamp = timestamp:gsub("%-00%-00T", "-01-01T")
-- just in case date precision is missing
dprec = dprec or 11
-- override more precise dates if required dateformat is year alone:
if df == "y" and dprec > 9 then dprec = 9 end
-- complex date only deals with precisions from 6 to 11, so clip range
dprec = dprec>11 and 11 or dprec
dprec = dprec<6 and 6 or dprec
-- BC format is "BC" or "BCE"
bcf = (bcf or ""):upper
-- plaindate only needs the first letter (y/n/a)
pd = (pd or ""):sub(1,1):lower
if pd == "" or pd == "n" or pd == "f" or pd == "0" then pd = false end
-- in case language isn't passed
lang = lang or findLang.code
-- set adj as empty if nil
adj = adj or ""
-- extract the day, month, year from the timestamp
local bc = timestamp:sub(1, 1)=="-" and "BC" or ""
local year, month, day = timestamp:match("[+-](%d*)-(%d*)-(%d*)T")
local iso = tonumber(year) -- if year is missing, let it throw an error
-- this will adjust the date format to be compatible with cdate
-- possible formats are Y, YY, YYY0, YYYY, YYYY-MM, YYYY-MM-DD
if dprec == 6 then iso = math.floor( (iso - 1) / 1000 ) + 1 end
if dprec == 7 then iso = math.floor( (iso - 1) / 100 ) + 1 end
if dprec == 8 then iso = math.floor( iso / 10 ) .. "0" end
if dprec == 10 then iso = year .. "-" .. month end
if dprec == 11 then iso = year .. "-" .. month .. "-" .. day end
-- add "circa" (Q5727902) from "sourcing circumstances" (P1480)
local sc = not pd and qualifiers and qualifiers.P1480
if sc then
for k1, v1 in pairs(sc) do
if v1.datavalue and v1.datavalue.value.id == "Q5727902" then
adj = "circa"
break
end
end
end
-- deal with Julian dates:
-- no point in saying that dates before 1582 are Julian - they are by default
-- doesn't make sense for dates less precise than year
-- we can suppress it by setting |plaindate, e.g. for use in constructing categories.
local calendarmodel = ""
if tonumber(year) > 1582
and dprec > 8
and not pd
and model == "http://www.wikidata.org/entity/Q1985786" then
calendarmodel = "julian"
end
if not cdate then
cdate = require("Module:Complex date")._complex_date
end
local fdate = cdate(calendarmodel, adj, tostring(iso), dp[dprec], bc, "", "", "", "", lang, 1)
-- this may have QuickStatements info appended to it in a div, so remove that
fdate = fdate:gsub(' <div>[^<]*</div>', '')
-- it may also be returned wrapped in a microformat, so remove that
fdate = fdate:gsub("<[^>]*>", "")
-- there may be leading zeros that we should remove
fdate = fdate:gsub("^0*", "")
-- if a plain date is required, then remove any links (like BC linked)
if pd then
fdate = fdate:gsub("%[%[.*|", ""):gsub("]]", "")
end
-- if 'circa', use the abbreviated form *** internationalise later ***
fdate = fdate:gsub('circa ', '<abbr title="circa">c.</abbr>&nbsp;')
-- deal with BC/BCE
if bcf == "BCE" then
fdate = fdate:gsub('BC', 'BCE')
end
-- deal with mdy format
if df == "mdy" then
fdate = fdate:gsub("(%d+) (%w+) (%d+)", "%2 %1, %3")
end
-- deal with adjectival form *** internationalise later ***
if pd == "a" then
fdate = fdate:gsub(' century', '-century')
end
return fdate
end  
---
-- parseParam takes a (string) parameter, e.g. from the list of arguments,
-- and makes "false", "no", and "0" into the (boolean) false
-- it makes the empty string and nil into the (boolean) value passed as default
-- allowing the parameter to be true or false by default.
-- It returns a boolean.
---
-- Dependencies:
---
local parseParam = function(param, default)