webmcp
view framework/env/format/time.lua @ 425:beb1e7925a52
Stack traceback for "coro" (initializers/finalizers)
| author | jbe | 
|---|---|
| date | Tue Jan 12 20:03:17 2016 +0100 (2016-01-12) | 
| parents | db7ad8e4f78b | 
| children | 
 line source
     1 --[[--
     2 text =                           -- text with the value formatted as a time, according to the locale settings
     3 format.time(
     4   value,                         -- a time, a timestamp or nil
     5   {
     6     nil_as       = nil_text,     -- text to be returned for a nil value
     7     hide_seconds = hide_seconds  -- set to TRUE to hide seconds
     8   }
     9 )
    11 Formats a time or timestamp as a time, according to the locale settings.
    13 --]]--
    15 function format.time(value, options)
    16   local options = options or {}
    17   if value == nil then
    18     return options.nil_as or ""
    19   end
    20   if not (
    21     atom.has_type(value, atom.time) or
    22     atom.has_type(value, atom.timestamp)
    23   ) then
    24     error("Value passed to format.time(...) is neither a time, a timestamp, nor nil.")
    25   end
    26   if value.invalid then
    27     return "invalid"
    28   end
    29   local result = locale.get("time_format") or "HH:MM{:SS}"
    30   if options.hide_seconds then
    31     result = string.gsub(result, "{[^{|}]*}", "")
    32   else
    33     result = string.gsub(result, "{([^{|}]*)}", "%1")
    34   end
    35   local am_pm
    36   local hour = value.hour
    37   result = string.gsub(result, "{([^{|}]*)|([^{|}]*)}", function(am, pm)
    38     if hour >= 12 then
    39       am_pm = pm
    40     else
    41       am_pm = am
    42     end
    43     return "{|}"
    44   end)
    45   if am_pm and hour > 12 then
    46     hour = hour - 12
    47   end
    48   if am_pm and hour == 0 then
    49     hour = 12
    50   end
    51   result = string.gsub(result, "HH", function()
    52     return format.decimal(hour, { digits = 2 })
    53   end)
    54   result = string.gsub(result, "MM", function()
    55     return format.decimal(value.minute, { digits = 2 })
    56   end)
    57   result = string.gsub(result, "SS", function()
    58     return format.decimal(value.second, { digits = 2 })
    59   end)
    60   if am_pm then
    61     result = string.gsub(result, "{|}", am_pm)
    62   end
    63   return result
    64 end
