webmcp

diff framework/env/format/interval.lua @ 106:bbfbbddf13ad

Support for intervals
author jbe
date Sun Nov 04 04:55:22 2012 +0100 (2012-11-04)
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/framework/env/format/interval.lua	Sun Nov 04 04:55:22 2012 +0100
     1.3 @@ -0,0 +1,65 @@
     1.4 +--[[--
     1.5 +text =                 -- text with the value formatted as a time, according to the locale settings
     1.6 +format.interval(
     1.7 +  value,               -- a time, a timestamp or nil
     1.8 +  {
     1.9 +    nil_as = nil_text  -- text to be returned for a nil value
    1.10 +  }
    1.11 +)
    1.12 +
    1.13 +Formats an interval, according to the locale settings.
    1.14 +
    1.15 +--]]--
    1.16 +
    1.17 +function format.interval(value, options)
    1.18 +  local options = options or {}
    1.19 +  if value == nil then
    1.20 +    return options.nil_as or ""
    1.21 +  end
    1.22 +  if not atom.has_type(value, atom.interval) then
    1.23 +    error("Value passed to format.interval(...) is neither an interval, nor nil.")
    1.24 +  end
    1.25 +  if value.invalid then
    1.26 +    return "invalid"
    1.27 +  end
    1.28 +  local parts = {}
    1.29 +  if value.years ~= 0 then
    1.30 +    parts[#parts+1] = tostring(value.years)
    1.31 +    if value.years == 1 or value.years == -1 then
    1.32 +      parts[#parts+1] = "year"  -- TODO: localization
    1.33 +    else
    1.34 +      parts[#parts+1] = "years"  -- TODO: localization
    1.35 +    end
    1.36 +  end
    1.37 +  if value.months ~= 0 then
    1.38 +    parts[#parts+1] = tostring(value.months)
    1.39 +    if value.months == 1 or value.months == -1 then
    1.40 +      parts[#parts+1] = "month"  -- TODO: localization
    1.41 +    else
    1.42 +      parts[#parts+1] = "months"  -- TODO: localization
    1.43 +    end
    1.44 +  end
    1.45 +  if value.days ~= 0 then
    1.46 +    parts[#parts+1] = tostring(value.days)
    1.47 +    if value.days == 1 or value.days == -1 then
    1.48 +      parts[#parts+1] = "day"  -- TODO: localization
    1.49 +    else
    1.50 +      parts[#parts+1] = "days"  -- TODO: localization
    1.51 +    end
    1.52 +  end
    1.53 +  if options.hide_seconds then
    1.54 +    parts[#parts+1] = string.format(
    1.55 +      "%02i:%02i",
    1.56 +      value.hours,
    1.57 +      math.abs(value.minutes) -- NOTE: hours and minutes always have equal sign
    1.58 +     )
    1.59 +  else
    1.60 +    parts[#parts+1] = string.format(
    1.61 +      "%02i:%02i:%02i",
    1.62 +      value.hours,
    1.63 +      math.abs(value.minutes),  -- NOTE: hours and minutes always have equal sign
    1.64 +      math.abs(value.seconds)   -- NOTE: hours and seconds always have equal sign
    1.65 +    )
    1.66 +  end
    1.67 +  return table.concat(parts, " ")
    1.68 +end

Impressum / About Us