Module:DateInterval

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Jump to navigation Jump to search

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

local p = {}

local function calculateDate(date, interval, time, timezone)
    local currentDate = os.time()
    local startDate = os.time{year=date.year, month=date.month, day=date.day, hour=time.hour, min=time.minute, sec=0, isdst=false}

    if timezone ~= "" then
        local timezoneOffset = os.difftime(os.time(os.date("!*t", startDate)), os.time(os.date("*t", startDate)))
        local timezoneCustomOffset = tonumber(timezone:match("([%-%+]%d%d):?%d*")) * 3600 or 0
        startDate = startDate + timezoneOffset - timezoneCustomOffset
    end

    local secondsElapsed = currentDate - startDate
    local intervalsElapsed = math.floor(secondsElapsed / (86400 * interval))

    local newDateTimestamp = startDate + (intervalsElapsed * 86400 * interval)
    local newDate = os.date("*t", newDateTimestamp)

    return newDate
end

function p.dateInterval(frame)
    local args = frame:getParent().args
    local date = args.date or ""
    local interval = tonumber(args.interval) or 7

    local year, month, day = date:match("(%d%d%d%d)%-(%d%d)%-(%d%d)")
    if not year or not month or not day then
        return "Error: Invalid date format. Please use YYYY-MM-DD."
    end

    local time = args.time or "00:00"
    local hour, minute = time:match("(%d%d?):(%d%d)")
    if not hour or not minute then
        return "Error: Invalid time format. Please use hh:mm."
    end

    local timezone = args.timezone or ""

    local dateTable = {year = tonumber(year), month = tonumber(month), day = tonumber(day)}
    local timeTable = {hour = tonumber(hour), minute = tonumber(minute)}
    local resultDate = calculateDate(dateTable, interval, timeTable, timezone)

    local formattedDate = os.date("%B %d, %Y", os.time(resultDate))
    formattedDate = formattedDate:gsub(' 0',' ')

    return formattedDate
end

return p