Module:TimeSpan: Difference between revisions

Add two toString functions
(Add two extra constructors)
(Add two toString functions)
Line 1: Line 1:
local TimeSpan = {}
local TimeSpan = {}
local StringBuilder = require('Module:StringBuilder')


-- Metatable to make instances of TimeSpan readonly
-- Metatable to make instances of TimeSpan readonly
Line 88: Line 90:


function TimeSpan:toString()
function TimeSpan:toString()
local sb = StringBuilder.new()
local days = self:getDays()
local hours = self:getHours()
local minutes = self:getMinutes()
local seconds = self:getSeconds()


    local milliseconds = totalMilliseconds % 1000
    totalMilliseconds = (totalMilliseconds - milliseconds) / 1000
    local seconds = totalMilliseconds % 60
    totalMilliseconds = (totalMilliseconds - seconds) / 60
    local minutes = totalMilliseconds % 60
    totalMilliseconds = (totalMilliseconds - minutes) / 60
    local hours = totalMilliseconds % 24
    local days = (totalMilliseconds - hours) / 24
    local parts = {}
     if days > 0 then
     if days > 0 then
         table.insert(parts, formatTime(days, "."))
         sb:append(string.format("%d.", days))
     end
     end
     table.insert(parts, formatTime(hours, ":"))
      
    table.insert(parts, formatTime(minutes, ":"))
    sb:append(string.format("%02d:%02d:%02d", hours, minutes, seconds))
     table.insert(parts, formatTime(seconds, ""))
      
     if milliseconds > 0 then
     if milliseconds > 0 then
         table.insert(parts, "." .. string.format("%03d", milliseconds))
         sb:append(string.format(".%03d", milliseconds))
     end
     end


     return table.concat(parts)
     return sb:toString()
end
 
function TimeSpan:toStringLong()
local sb = StringBuilder.new()
local days = self:getDays()
local hours = self:getHours()
local minutes = self:getMinutes()
local seconds = self:getSeconds()
local milliseconds = self:getMilliseconds()
local output = {}
if days > 0 then
table.insert(output, string.format('%d day%s', days, (days > 1) and "s" or ""))
end
if hours > 0 then
table.insert(output, string.format('%d hour%s', hours, (hours > 1) and "s" or ""))
end
if minutes > 0 then
table.insert(output, string.format('%d minute%s', minutes, (minutes > 1) and "s" or ""))
end
if seconds > 0 then
table.insert(output, string.format('%d second%s', seconds, (seconds > 1) and "s" or ""))
end
if milliseconds > 0 then
table.insert(output, string.format('%d second%s', milliseconds, (milliseconds > 1) and "s" or ""))
end
return table.concat(output, ", ")
end
end


915

edits