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