2012-11-05 34 views
0

以下是有問題的方法。RoR - Time.strptime問題

def published_at_setter 
    self.published_at = Time.strptime("#{@date} #{@time}", "%m/%d/%Y %I:%M %p") 
    puts " ~~~~~~~~~~~~~~~~~~~ #{@date} #{@time} ~~~~~~~~~~~~~~~~ #{self.published_at}" 
end 

With @date =「09/11/2012」and @time「01:45 AM」我在webbrick控制檯中得到了這個。 WFT?

~~~~~~~~~~~~~~~~~~~ 09/11/2012 01:45 AM ~~~~~~~~~~~~~~~~ 2012-09-11 06:45:00 UTC 

在rails console中,我得到了預期的結果。 「2012-09-11 01:45:00 -0500」

+0

你試過了'strftime'嗎?這裏是文檔http://apidock.com/ruby/DateTime/strftime:它返回一個字符串,'strptime'似乎返回一個Date對象(http://apidock.com/ruby/DateTime/strptime/class) – MrYoshiji

+0

我的任務是採取一個字符串,如「09/11/2012 01:45 AM」並將其轉換爲DateTime,因此您可以看到帶有Time.strptime的插值字符串。我不確定strftime如何工作,如果我有一個字符串開始。 –

+0

你有沒有試過time.localtime而不只是時間 – RadBrad

回答

2

而不是Time.strptime,您應該使用Time.zone.parse

def published_at_setter 
    self.published_at = Time.zone.parse("#{@date} #{@time}") 
    puts " ~~~~~~~~~~~~~~~~~~~ #{@date} #{@time} ~~~~~~~~~~~~~~~~ #{self.published_at}" 
end 
+0

謝謝賈森,我有想過這是一個時區問題,但不知道該怎麼做。 –