Class: Time

Inherits:
Object show all
Defined in:
lib/utilrb/time/to_hms.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_hms(string) ⇒ Object

Creates a Time object from a h:m:s.ms representation. The following formats are allowed: s, s.ms, m:s, m:s.ms, h:m:s, h:m:s.ms



52
53
54
55
# File 'lib/utilrb/time/to_hms.rb', line 52

def self.from_hms(string)
	h, m, s, ms = *hms_decomposition(string)
	Time.at(h * 3600 + m * 60 + s, 1000 * ms)
end

.hms_decomposition(string) ⇒ Object



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
# File 'lib/utilrb/time/to_hms.rb', line 8

def self.hms_decomposition(string)
	unless string =~ /(?:^|:)0*(\d*)(?:$|\.(\d*)$)/
 raise ArgumentError, "#{string} found, expected [[h:]m:]s[.ms]"
	end
	hm, ms = $`, ($2 || "")

	s = if $1.empty? then 0
 else Integer($1)
 end

	h, m = hm.split(':')
	if !m
 h, m = nil, h
	end

	if m
 m =~ /^0*(\d*)$/
 m = $1
	end
	m = if !m || m.empty? then 0
 else Integer(m)
 end

	if h
 h =~ /^0*(\d*)$/
 h = $1
	end
	h = if !h || h.empty? then 0
 else Integer(h)
 end

	ms = if ms =~ /^0*$/ then 0
  else
		 unless ms =~ /^(0*)(\d+)$/
   raise ArgumentError, "found #{string}, expected a number"
		 end
		 Integer($2) * (10 ** (3 - ($2.length + $1.length)))
  end

	[h, m, s, ms]
end

Instance Method Details

#to_hmsObject

Converts this time into a h:m:s.ms representation



3
4
5
6
# File 'lib/utilrb/time/to_hms.rb', line 3

def to_hms
	sec, usec = tv_sec, tv_usec
	"%i:%02i:%02i.%03i" % [sec / 3600, (sec % 3600) / 60, sec % 60, usec / 1000]
end