jbe/bsw@0: --[[-- jbe@108: text = -- text with the value formatted as a time, according to the locale settings jbe/bsw@0: format.time( jbe@108: value, -- a time, a timestamp or nil jbe/bsw@0: { jbe@108: nil_as = nil_text, -- text to be returned for a nil value jbe@108: hide_seconds = hide_seconds -- set to TRUE to hide seconds jbe/bsw@0: } jbe/bsw@0: ) jbe/bsw@0: jbe/bsw@0: Formats a time or timestamp as a time, according to the locale settings. jbe/bsw@0: jbe/bsw@0: --]]-- jbe/bsw@0: jbe/bsw@0: function format.time(value, options) jbe/bsw@0: local options = options or {} jbe/bsw@0: if value == nil then jbe/bsw@0: return options.nil_as or "" jbe/bsw@0: end jbe/bsw@0: if not ( jbe/bsw@0: atom.has_type(value, atom.time) or jbe/bsw@0: atom.has_type(value, atom.timestamp) jbe/bsw@0: ) then jbe/bsw@0: error("Value passed to format.time(...) is neither a time, a timestamp, nor nil.") jbe/bsw@0: end jbe/bsw@0: if value.invalid then jbe/bsw@0: return "invalid" jbe/bsw@0: end jbe/bsw@0: local result = locale.get("time_format") or "HH:MM{:SS}" jbe/bsw@0: if options.hide_seconds then jbe/bsw@0: result = string.gsub(result, "{[^{|}]*}", "") jbe/bsw@0: else jbe@105: result = string.gsub(result, "{([^{|}]*)}", "%1") jbe/bsw@0: end jbe/bsw@0: local am_pm jbe/bsw@0: local hour = value.hour jbe@105: result = string.gsub(result, "{([^{|}]*)|([^{|}]*)}", function(am, pm) jbe@105: if hour >= 12 then jbe/bsw@0: am_pm = pm jbe/bsw@0: else jbe/bsw@0: am_pm = am jbe/bsw@0: end jbe/bsw@0: return "{|}" jbe/bsw@0: end) jbe/bsw@0: if am_pm and hour > 12 then jbe/bsw@0: hour = hour - 12 jbe/bsw@0: end jbe@109: if am_pm and hour == 0 then jbe@109: hour = 12 jbe@109: end jbe/bsw@0: result = string.gsub(result, "HH", function() jbe/bsw@0: return format.decimal(hour, { digits = 2 }) jbe/bsw@0: end) jbe/bsw@0: result = string.gsub(result, "MM", function() jbe/bsw@0: return format.decimal(value.minute, { digits = 2 }) jbe/bsw@0: end) jbe/bsw@0: result = string.gsub(result, "SS", function() jbe/bsw@0: return format.decimal(value.second, { digits = 2 }) jbe/bsw@0: end) jbe/bsw@0: if am_pm then jbe/bsw@0: result = string.gsub(result, "{|}", am_pm) jbe/bsw@0: end jbe/bsw@0: return result jbe/bsw@0: end