2017-06-06 125 views
0

我執行此代碼:'Time.at(秒)' 給出不同的時間 '的級分(秒/ 60,秒%60)'

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(':') 

我得到:

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 

這是非常不同的。爲什麼Time.at(seconds)增加5小時30分鐘?

+0

嘗試'Time.zone.at(T2).strftime( 「%H:%M:%S」)' –

+0

這是因爲你的時區 – fangxing

+0

@ Md.FarhanMemon嘗試「Time.zone .AT(T2).strftime( 「%H:%M:%S」)」。它給了我一個未定義的方法'區域'的時間:類(NoMethodError) – Tim

回答

2

爲什麼Time.at(seconds)需要5小時30分鐘?

因爲你正在比較蘋果和橘子。

DateTime.strptimeUTC返回一個DateTime實例。如果你不提供一個日期,它採用今天的日期

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

Time.at當地時區返回Time實例的基礎上,從紀元秒數(1月1日1970年):

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