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
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
# File 'lib/zena/use/dates.rb', line 256 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.
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'lib/zena/use/dates.rb', line 217 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 |