Module: N::TimeUtils

Defined in:
lib/glue/time.rb

Overview

General time utilities collection

Implement as a module to avoid class polution. You can still Ruby’s advanced features to include the module in your class. Passing the object to act upon allows to check for nil, which isn’t possible if you use self.

TODO

  • SOS: add test units.

  • add aliases for those methods in Kernel ?

Constant Summary collapse

NOW =
Time.now
NEVER =
Time.mktime(2038)
ZERO =
Time.mktime(1972)

Class Method Summary collapse

Class Method Details

.date_time(time) ⇒ Object

Convert the time to a nice String representation.



29
30
31
32
# File 'lib/glue/time.rb', line 29

def self.date_time(time)
	return nil unless time 
	return time.strftime("%d-%m-%Y %H:%M")
end

.days_extrema(time1, time2 = nil) ⇒ Object

This method calculates the days extrema given two time objects. start time is the given time1 at 00:00:00 end time is the given time2 at 23:59:59:999

Input:

  • the two times (if only time1 is provided then you get an extrema of exactly one day extrema.

Output

  • the time range. you can get the start/end times using range methods.



46
47
48
49
50
51
52
# File 'lib/glue/time.rb', line 46

def self.days_extrema(time1, time2=nil)
	time2 = time1 if (not time2.valid? Time)
	time2 = NEVER if (time2 <= time1)
	start_time = Time.self.start_of_day(time1)
	end_time = self.end_of_day(time2)
	return (start_time..end_time)
end

.end_of_day(time) ⇒ Object

Set time to end of day



63
64
65
# File 'lib/glue/time.rb', line 63

def self.end_of_day(time)
	return Time.mktime(time.year, time.month, time.day, 23, 59, 59, 999)
end

.start_of_day(time) ⇒ Object

Set time to start of day



56
57
58
# File 'lib/glue/time.rb', line 56

def self.start_of_day(time)
	return Time.mktime(time.year, time.month, time.day, 0, 0, 0, 0)
end

.time_in_day_range(time, stime = ZERO, etime = NEVER) ⇒ Object

Returns true only if day of time is included in the range (stime..etime). Only year days are checked.



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/glue/time.rb', line 71

def self.time_in_day_range(time, stime=ZERO, etime=NEVER)
	if (etime <= stime)
		Logger.debug "Invalid end time (#{etime} < #{stime})" if $DBG
		etime = NEVER
	end

	stime = start_of_day(stime)
	etime = end_of_day(etime)

	return (stime..etime).include?(time)
end