webmcp
diff framework/env/format/time.lua @ 0:9fdfb27f8e67
Version 1.0.0
author | jbe/bsw |
---|---|
date | Sun Oct 25 12:00:00 2009 +0100 (2009-10-25) |
parents | |
children | fd31e0aa629a |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/framework/env/format/time.lua Sun Oct 25 12:00:00 2009 +0100 1.3 @@ -0,0 +1,60 @@ 1.4 +--[[-- 1.5 +text = -- text with the value formatted as a time, according to the locale settings 1.6 +format.time( 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 a time or timestamp as a time, according to the locale settings. 1.14 + 1.15 +--]]-- 1.16 + 1.17 +function format.time(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 ( 1.23 + atom.has_type(value, atom.time) or 1.24 + atom.has_type(value, atom.timestamp) 1.25 + ) then 1.26 + error("Value passed to format.time(...) is neither a time, a timestamp, nor nil.") 1.27 + end 1.28 + if value.invalid then 1.29 + return "invalid" 1.30 + end 1.31 + local result = locale.get("time_format") or "HH:MM{:SS}" 1.32 + if options.hide_seconds then 1.33 + result = string.gsub(result, "{[^{|}]*}", "") 1.34 + else 1.35 + result = string.gsub(result, "{([^|]*)}", "%1") 1.36 + end 1.37 + local am_pm 1.38 + local hour = value.hour 1.39 + result = string.gsub(result, "{([^{}]*)|([^{}]*)}", function(am, pm) 1.40 + if hour > 12 then 1.41 + am_pm = pm 1.42 + else 1.43 + am_pm = am 1.44 + end 1.45 + return "{|}" 1.46 + end) 1.47 + if am_pm and hour > 12 then 1.48 + hour = hour - 12 1.49 + end 1.50 + result = string.gsub(result, "HH", function() 1.51 + return format.decimal(hour, { digits = 2 }) 1.52 + end) 1.53 + result = string.gsub(result, "MM", function() 1.54 + return format.decimal(value.minute, { digits = 2 }) 1.55 + end) 1.56 + result = string.gsub(result, "SS", function() 1.57 + return format.decimal(value.second, { digits = 2 }) 1.58 + end) 1.59 + if am_pm then 1.60 + result = string.gsub(result, "{|}", am_pm) 1.61 + end 1.62 + return result 1.63 +end