Tim
Tim

Reputation: 81

'Time.at(seconds)' gives different time than 'fractions(seconds/60, seconds%60)'

I am executing this code:

t = DateTime.strptime('1:00:23', '%H:%M:%S')
t1 = DateTime.strptime('2:02:40', '%H:%M:%S')
t2 = t1.to_time - t.to_time
time_new = "#{(t2/3600).to_i}" + ":" +"#{((t2/60)%60).to_i}" + ":" + "#{(t2%60).to_i}"
time_units = time_new.split(':')

I get:

Time.at(t2).strftime("%H:%M:%S")
# => 06:32:17
"#{time_units[0]} hours, #{time_units[1]} minutes and #{time_units[2]} seconds"
# => 1 hours, 2 minutes and 17 seconds

which are very different. Why does Time.at(seconds) add 5 hours and 30 minutes?

Upvotes: 0

Views: 67

Answers (1)

Stefan
Stefan

Reputation: 114238

Why does Time.at(seconds) add 5 hours and 30 minutes?

Because you are comparing apples and oranges.

DateTime.strptime returns a DateTime instance in UTC. If you don't provide a date, it uses today's date:

DateTime.strptime('01:00:23')
#=> Tue, 06 Jun 2017 01:00:23 +0000
#   ^^^^^^^^^^^^^^^^          ^^^^^
#         today                UTC

Time.at returns a Time instance in your local time zone, based on the number of seconds since the epoch (1 January 1970):

Time.at(1 * 3600 + 23)
#=> 1970-01-01 02:00:23 +0100
#   ^^^^^^^^^^          ^^^^^
#   not today          not UTC

Upvotes: 2

Related Questions