webmcp

view framework/env/format/time.lua @ 108:08c107cc4fce

Documentation of "hide_seconds" flag for format.time and format.timestamp
author jbe
date Sun Nov 04 18:46:29 2012 +0100 (2012-11-04)
parents fd31e0aa629a
children db7ad8e4f78b
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 result = string.gsub(result, "HH", function()
49 return format.decimal(hour, { digits = 2 })
50 end)
51 result = string.gsub(result, "MM", function()
52 return format.decimal(value.minute, { digits = 2 })
53 end)
54 result = string.gsub(result, "SS", function()
55 return format.decimal(value.second, { digits = 2 })
56 end)
57 if am_pm then
58 result = string.gsub(result, "{|}", am_pm)
59 end
60 return result
61 end

Impressum / About Us