Module: Zena::Use::Dates::StringMethods
- Defined in:
- lib/zena/use/dates.rb
Constant Summary collapse
- SPLIT_STRING =
/[^0-9]+/
- SPLIT_FORMAT =
/[^\w%]*%/
Instance Method Summary collapse
-
#to_duration ⇒ Object
Convert a string of the form ‘1 month 4 days’ to the duration in seconds.
-
#to_utc(format, timezone = nil) ⇒ Object
Parse date : return an utc date from a string and an strftime format.
Instance Method Details
#to_duration ⇒ Object
Convert a string of the form ‘1 month 4 days’ to the duration in seconds. Valid formats are: y : Y : year : years M : month : months d : day : days h : hour : hours m : minute : minutes s : second : seconds
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/zena/use/dates.rb', line 249 def to_duration res = 0 val = 0 split(/\s+/).map {|e| e =~ /^(\d+)([a-zA-Z]+)$/ ? [$1,$2] : e }.flatten.map do |e| if e =~ /[0-9]/ val = e.to_i else if e[0..1] == 'mo' e = 'M' end res += val * case e[0..0] when 'y','Y' 31536000 when 'M' 2592000 when 'd' 86400 when 'h' 3600 when 'm' 60 when 's' 1 else 0 end val = 0 end end res end |
#to_utc(format, timezone = nil) ⇒ Object
Parse date : return an utc date from a string and an strftime format. With the current implementation, you can only use ‘.’, ‘-’, ‘ ’ or ‘:’ to separate the different parts in the format.
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
# File 'lib/zena/use/dates.rb', line 210 def to_utc(format, timezone=nil) elements = split(SPLIT_STRING) format = format.sub('T', ' ').split(SPLIT_FORMAT)[1..-1] if elements hash = {} elements.each_index do |i| hash[format[i]] = elements[i] end hash['Y'] ||= hash['y'] ? (hash['y'].to_i + 2000) : Time.now.year hash['H'] ||= 0 hash['M'] ||= 0 hash['S'] ||= 0 if hash['Y'] && hash['m'] && hash['d'] res = Time.utc(hash['Y'], hash['m'], hash['d'], hash['H'], hash['M'], hash['S']) begin timezone ? timezone.local_to_utc(res, true) : res rescue TZInfo::AmbiguousTime # Better a bad date then nothing res end else nil end else nil end rescue ArgumentError nil end |