Module:DTZ

From Islamical Commons
Jump to navigation Jump to search

Documentation for this module may be created at Module:DTZ/doc

--[[  
 
Format date/times with time zones. Input can be specified using the following
subset of ISO 8601:

YYYY-MM-DDTHH:MMZ       (UTC)
YYYY-MM-DDTHH:MM+HH     (hours ahead of UTC)
YYYY-MM-DDTHH:MM+HH:MM  (hours and minutes ahead of UTC)
YYYY-MM-DDTHH:MM-HH     (hours behind of UTC)
YYYY-MM-DDTHH:MM-HH:MM  (hours and minutes behind of UTC)

and similar strings with seconds included in the time:

YYYY-MM-DDTHH:MM:SSZ
YYYY-MM-DDTHH:MM:SS+HH
YYYY-MM-DDTHH:MM:SS+HH:MM
YYYY-MM-DDTHH:MM:SS-HH
YYYY-MM-DDTHH:MM:SS-HH:MM

]]

local p = {}

local Date = require('Module:DateI18n-585816189')
local errorcat = "[[Category:Incorrect use of DTZ]]"

local function format(year, month, day, hour, minute, second, tzhour, tzmin, lang)
    local result = Date._Date({year, month, day, hour, minute, second, tzhour, tzmin}, lang)
    if result == '' then
       return "invalid values in date/time" .. errorcat
    end
    return result
end

function p.DTZ(frame)
       local input = mw.text.trim(frame.args[1])
       local lang = frame:callParserFunction("int", "lang") -- user's language --
       local all, year, month, day, hour, minute, second = input:match("^((%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d))")
       if all == nil then
          all, year, month, day, hour, minute = input:match("^((%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d))")
         if all == nil then
            return "invalid date/time format" .. errorcat
         end
       end
       local tzhour, tzmin
       local rest = input:sub(all:len()+1)
       if rest == '' then
          return "missing timezone" .. errorcat
       end
       if rest:len() == 1 and rest:sub(1,1) == 'Z' then
          return format(year, month, day, hour, minute, second, '0', '', lang)
       end
       local tzsign
       tzsign, tzhour, tzmin = rest:match("^([+-])(%d%d):(%d%d)$")
       if tzsign == nil then
          tzsign, tzhour = rest:match("^([+-])(%d%d)$")
          if tzsign == nil then
            return "invalid timezone" .. errorcat
          end     
          tzmin = '00' -- work around a glitch in Module:Date --
       end
       if tzsign == '-' then
          tzhour = -1 * tzhour
       end
       return format(year, month, day, hour, minute, second, tzhour, tzmin, lang)
end

return p