Code Coverage
 
Lines
Covered
45.00% covered (danger)
45.00%
27 / 60
1
require 'date'
1
require 'time'
1
module TheFox
1
module Timr
1
module Helper
# This class should *NOT* replace [Time](http://ruby-doc.org/core-2.4.1/Time.html), [Date](http://ruby-doc.org/stdlib-2.4.1/libdoc/date/rdoc/Date.html) or [DateTime](http://ruby-doc.org/stdlib-2.4.1/libdoc/date/rdoc/DateTime.html).
1
class DateTimeHelper
# All methods in this block are static.
1
class << self
1
include TheFox::Timr::Error
# Convert String to Date.
1
def convert_date(date)
0
case date
when String
0
Time.parse(date).utc.to_date
when nil
0
Time.now.utc.to_date
end
end
# Convert String to Time.
1
def convert_time(time)
0
case time
when String
0
Time.parse(time).utc
when nil
0
Time.now.utc
end
end
# Parse an argv Array.
#
# Create a `from` and `to` for a day.
1
def parse_day_argv(argv)
0
day = argv.shift
0
from = Time.parse("#{day} 00:00:00")
0
to = Time.parse("#{day} 23:59:59")
0
[from, to]
end
# Parse an argv Array.
#
# Create a `from` and `to` for a month.
1
def parse_month_argv(argv)
0
parts = argv.shift.split('-').map{ |s| s.to_i }
0
if parts.count == 1
0
y = Date.today.year
0
m = parts.first
else
0
y, m = parts
end
0
if y < 2000 # shit
0
y += 2000
end
0
start_date = Date.new(y, m, 1)
0
end_date = Date.new(y, m, -1)
0
from = Time.parse("#{start_date.strftime('%F')} 00:00:00")
0
to = Time.parse("#{end_date.strftime('%F')} 23:59:59")
0
[from, to]
end
# Parse an argv Array.
#
# Create a `from` and `to` for a year.
1
def parse_year_argv(argv)
0
y = argv.shift
0
if y
0
y = y.to_i
else
0
y = Date.today.year
end
0
if y < 2000 # shit
0
y += 2000
end
0
start_date = Date.new(y, 1, 1)
0
end_date = Date.new(y, 12, -1)
0
from = Time.parse("#{start_date.strftime('%F')} 00:00:00")
0
to = Time.parse("#{end_date.strftime('%F')} 23:59:59")
0
[from, to]
end
# Create a Time instance from a Hash.
#
# Options:
#
# - `:date` String
# - `:time` String
1
def get_datetime_from_options(options = Hash.new)
8
date_opt = options.fetch(:date, nil)
8
time_opt = options.fetch(:time, nil)
8
if date_opt && !time_opt
1
raise DateTimeHelperError, 'You also need to set a time when giving a date.'
end
7
datetime_a = []
7
if date_opt
4
datetime_a << date_opt
end
7
if time_opt
4
datetime_a << time_opt
end
7
if datetime_a.count > 0
4
datetime_s = datetime_a.join(' ')
4
Time.parse(datetime_s).utc
else
3
Time.now.utc
end
end
end
end # class DateTimeHelper
end # module Helper
end # module Timr
end # module TheFox