Module: Ptf::Date

Defined in:
lib/ptf/date.rb

Class Method Summary collapse

Class Method Details

.create_datetime_from_str(str) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 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) ⇒ Object

Raises:

  • (ArgumentError)


5
6
7
8
9
# 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) ⇒ Object

Raises:

  • (ArgumentError)


47
48
49
50
51
52
53
54
55
56
57
# 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