2009-09-07 27 views

回答

0
require 'time' 
x = "2009/04/16 19:52:30" 
begin 
    y = Time.parse(x) 
    [y.year, y.month, y.day] # => [2009, 4, 16] 
rescue ArgumentError 
    puts "cannot parse date: #{x}" 
end 
1

字符串是如何格式化的?您可以將日期時間字符串轉換爲日期時間對象,然後調用實例方法。

require 'time' 
x = "2009/04/16 19:52:30" #grab your datetime string from the database and assign it 

y = DateTime.strptime(x, "%Y/%m/%d %H:%M:%S") #create a new date object 

那麼簡單y.day()產量:

y.day() = 16 

和y.hour():

y.hour() = 19 

FYI從未實際使用Ruby的多,所以這是我擺脫了與控制檯一起玩,所以希望這有助於擺脫一些光。