1,048
edits
(Add two extra constructors) |
m (Small fix to toStringLong) |
||
(4 intermediate revisions by the same user not shown) | |||
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 38: | Line 40: | ||
end | end | ||
function TimeSpan. | function TimeSpan.fromMilliseconds(milliseconds) | ||
return TimeSpan.new(0, 0, 0, 0, (milliseconds or 0)) | return TimeSpan.new(0, 0, 0, 0, (milliseconds or 0)) | ||
end | end | ||
function TimeSpan. | function TimeSpan.fromSeconds(seconds) | ||
local totalMilliseconds = (seconds or 0) * MillisecondsPerSecond | local totalMilliseconds = (seconds or 0) * MillisecondsPerSecond | ||
return TimeSpan.new(0, 0, 0, 0, totalMilliseconds) | return TimeSpan.new(0, 0, 0, 0, totalMilliseconds) | ||
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() | |||
if days > 0 then | |||
sb:append(string.format("%d.", days)) | |||
end | |||
sb:append(string.format("%02d:%02d:%02d", hours, minutes, seconds)) | |||
if milliseconds > 0 then | |||
sb:append(string.format(".%03d", milliseconds)) | |||
end | |||
return sb:toString() | |||
end | |||
function TimeSpan:toStringLong() | |||
-- Fast path if there's less than a minute's worth of time. | |||
local totalSeconds = self:getTotalSeconds() | |||
if totalSeconds < 60 then | |||
if math.floor(totalSeconds) == 0 then | |||
return string.format('0 seconds') | |||
end | |||
-- Special case to show actiontime related numbers. | |||
return string.format('%.2f seconds', totalSeconds) | |||
end | |||
-- Long path that outputs the entire TimeSpan | |||
local output = {} | |||
local days = self:getDays() | |||
local hours = self:getHours() | |||
local minutes = self:getMinutes() | |||
local seconds = self:getSeconds() | |||
local milliseconds = self:getMilliseconds() | |||
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('%.2f second%s', seconds, (seconds > 1) and "s" or "")) | |||
end | |||
return table.concat(output, ", ") | |||
end | end | ||
edits