module Ptf::Date
Public Class Methods
create_datetime_from_str(str)
click to toggle source
# File lib/ptf/date.rb, line 11 def create_datetime_from_str(str) begin dt = str_to_datetime(str) return dt rescue end time_regex = /([0-2]?\d):([0-5]\d):?([0-5]\d)?/ # Check if given time 12:21(:21) match = time_regex.match(str).to_a if !match.nil? && (match.length == 3 || match.length == 4) now = DateTime.now return DateTime.new(now.year, now.month, now.day, match[1].to_i, match[2].to_i, 0, now.zone) end # Check if given date 12/27(/[15|2015]) date_regex = /^([01]?\d)\/([0-3]?\d)\/?(\d\d\d\d|\d\d)?$/ match = date_regex.match(str) if !match.nil? && (match.length == 3 || match.length == 4) now = DateTime.now if !match[3].nil? && match[3].length == 2 year = 2000 + match[3].to_i elsif !match[3].nil? year = match[3].to_i end return DateTime.new((match[3].nil? ? now.year : year), match[1].to_i, match[2].to_i, 12, 0, 0, now.zone) end nil end
datetime_to_str(datetime)
click to toggle source
# File lib/ptf/date.rb, line 5 def datetime_to_str(datetime) raise ArgumentError, "DateTime expected. Received #{datetime.class} instead." unless datetime.is_a? DateTime datetime.strftime('%Y%m%d%H%M%S') end
str_to_datetime(str)
click to toggle source
# File lib/ptf/date.rb, line 47 def str_to_datetime(str) date_regex = /^(\d\d\d\d)([01]\d)([0-3]\d)([0-2]\d)([0-5]\d)([0-5]\d)?$/ regex_match = date_regex.match(str) raise ArgumentError, "Improperly formatted datetime string, #{str}." unless regex_match.to_a.length == 7 _, year, month, day, hour, minute, second = regex_match.to_a DateTime.new(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, second.to_i) end