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
|
# File 'lib/datetime_diff.rb', line 5
def self.diff_to_s mls, format=nil
mls = (mls * 1000).to_i
s = m = h = d = 0
if mls >= 1000
s = (mls-(mls%1000))/1000
mls = mls%1000
end
if s >= 60
m = (s-(s%60))/60
s = s%60
end
if m >= 60
h = (m-(m%60))/60
m = m%60
end
if h >= 24
d = (h-(h%24))/24
h = h%24
end
t = {D: d,
H: h.to_s.rjust(2,"0"),
M: m.to_s.rjust(2,"0"),
S: s.to_s.rjust(2,"0"),
m: mls.to_s.rjust(3,"0")}
if format
r = ""
values = format.scan(/\%\S[\S|\s]{1,3}*?(?!%)/)
for xV in values
if values.index(xV) + 1 == values.size
r += "#{t[xV.gsub("%","").to_sym]}#{format.scan(/(?<=#{xV})[\s|\S]*?$/)[0]}"
else
r += "#{t[xV.gsub("%","").to_sym]}#{format.scan(/(?<=#{xV})[\s|\S]*?(?=\%)/)[0]}"
end
end
r
else
r = ""
r += "#{d} #{d > 1 ? "days" : "day"} "
r += "#{h} #{h > 1 ? "hours" : "hour"} "
r += "#{m} #{m > 1 ? "minutes" : "minute"} "
r += "#{s} #{s > 1 ? "seconds" : "second"} "
r += "#{mls} #{mls > 1 ? "milliseconds" : "millisecond"} "
r.strip.gsub(/\s{2,}/," ")
end
end
|