webmcp
view framework/env/format/date.lua @ 155:185e944182cb
Better C macros for null-marker in JSON library
| author | jbe | 
|---|---|
| date | Thu Jul 31 03:18:04 2014 +0200 (2014-07-31) | 
| parents | 9fdfb27f8e67 | 
| children | 
 line source
     1 --[[--
     2 text =                 -- text with the value formatted as a date, according to the locale settings
     3 format.date(
     4   value,               -- a date, a timestamp or nil
     5   {
     6     nil_as = nil_text  -- text to be returned for a nil value
     7   }
     8 )
    10 Formats a date or timestamp as a date, according to the locale settings.
    12 --]]--
    14 function format.date(value, options)
    15   local options = options or {}
    16   if value == nil then
    17     return options.nil_as or ""
    18   end
    19   if not (
    20     atom.has_type(value, atom.date) or
    21     atom.has_type(value, atom.timestamp)
    22   ) then
    23     error("Value passed to format.date(...) is neither a date, a timestamp, nor nil.")
    24   end
    25   if value.invalid then
    26     return "invalid"
    27   end
    28   local result = locale.get("date_format") or "YYYY-MM-DD"
    29   result = string.gsub(result, "YYYY", function()
    30     return format.decimal(value.year, { digits = 4 })
    31   end)
    32   result = string.gsub(result, "YY", function()
    33     return format.decimal(value.year % 100, { digits = 2 })
    34   end)
    35   result = string.gsub(result, "Y", function()
    36     return format.decimal(value.year)
    37   end)
    38   result = string.gsub(result, "MM", function()
    39     return format.decimal(value.month, { digits = 2 })
    40   end)
    41   result = string.gsub(result, "M", function()
    42     return format.decimal(value.month)
    43   end)
    44   result = string.gsub(result, "DD", function()
    45     return format.decimal(value.day, { digits = 2 })
    46   end)
    47   result = string.gsub(result, "D", function()
    48     return format.decimal(value.day)
    49   end)
    50   return result
    51 end
