ruby - Diff between two time -
How is the difference between two times in Ruby calculated? For example:
I have this time as a string
time1 = '08: 00 'time2 =' 12: 00 '
Understand that time is 1 positive and time 2 is negative (seems like working hours, I work 8 hours a day, and 12 hours a day for another day Looks like), I want to do something like this:
diff = time.parse (time1) - time.parse (time 2) time. (Difference) .gmtime.strftime ('% H:% M ') # Something like "-04: 00" is expected to be received at # but the result is "20:00"
To understand what is wrong with your code, let's execute it one by one:
▶ time.preparation ('08: 00 ') - time. Parse ('12: 00 ') # = & gt; -14400.0
seconds, huh okay.
▶ Time. (Time.only ('08: 00 ') - Time. From (' 12: 00 ')) => 1969-12-31 21:00:00 +0100
Wow, Time.at
There is no way of our dreams. Apart from this, I do not know the hours in format in the standard library in the % H:% M
format. But:
▶ sprintf "% + 03i:% 02i", -14400 / 3600, -14400 / 60% 60 # hours, minute # = & gt; "-04: 00"
The only problem is a hint:
▶ time1 = '06: 28 '; Time 2 = '12: 00 '▶ difference = time.parse (time 1) - time.parse (time 2) ▶ sprintiff "% + 03i:% 02i", (diff / diff.abs) * (diff.abs / 3600), Diff.abs / 60% 60 # = & gt; "-05: 32"
Hope this will be helpful.
UPD: For those who like Makarpatching:
class time def diff_hours Other Returns Zero until time === Other Diff = self - other sprintf "% + 03i:% 02i", (diff / diff.abs) * (diff.abs / 3600), diff stomach / 60% 60 end end # = & gt; : Diff_hours ▶ Time. From ('06: 32 '). Diff_hours Time. From ('12: 00 ') # = & gt; "-05: 28"
Comments
Post a Comment