forked from testmycode/tmc-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate_and_time_utils.rb
64 lines (53 loc) · 1.19 KB
/
date_and_time_utils.rb
1
2
3
4
5
6
7
8
9
10
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
module DateAndTimeUtils
def self.to_time(input, options = {})
options = {
prefer_end_of_day: false
}.merge options
d = input
if d.blank?
return nil
end
d = parse_date_or_time(d) if d.is_a?(String)
if d.is_a? Date
if options[:prefer_end_of_day]
d = d.end_of_day
else
d = d.beginning_of_day
end
elsif !d.is_a?(Time)
fail "Invalid date or time: #{input}"
end
d
end
def self.parse_date_or_time(input)
s = input.strip
if s =~ /^(\d+)\.(\d+)\.(\d+)(.*)$/
s = "#{$3}-#{$2}-#{$1}#{$4}"
end
result = nil
begin
if s =~ /^\d+-\d+-\d+$/
result = Date.parse(s)
elsif s =~ /^\d+-\d+-\d+\s+\d+:\d+(:?:\d+(:?\.\d+)?)?(:?\s+\S+)?$/
result = Time.zone.parse(s)
end
rescue
raise "Invalid date/time: #{input}"
end
fail "Cannot parse date/time: #{input}" unless result
result
end
def self.to_utc_str(time, options = {})
t = to_time(time, options)
if !t.nil?
t.utc.strftime('%Y-%m-%d %H:%M:%S.%6N %Z')
else
t
end
end
def self.looks_like_date_or_time(str)
!!parse_date_or_time(str)
rescue
false
end
end