1
我正在尋找從MySQL取得日期時間字符串的最佳方式,將其在Ruby中爆炸並在單獨的元素中返回月份,日期和年份。在Ruby中將日期字符串爆炸爲單獨的跨度元素
我正在尋找從MySQL取得日期時間字符串的最佳方式,將其在Ruby中爆炸並在單獨的元素中返回月份,日期和年份。在Ruby中將日期字符串爆炸爲單獨的跨度元素
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
字符串是如何格式化的?您可以將日期時間字符串轉換爲日期時間對象,然後調用實例方法。
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的多,所以這是我擺脫了與控制檯一起玩,所以希望這有助於擺脫一些光。