日期与时间

日期与时间 #

当前时间

inspect 用于获得当前时间的字符串

time1 = Time.new
puts time1.inspect

time2 = Time.now
puts time2.inspect

获得秒为单位的时间戳

puts time1.to_i

获得时间对应的字段

puts time1.year
puts time1.month
puts time1.day
puts time1.wday

指定时区

puts Time.local(2008, 7, 8)
puts Time.local(2008, 7, 8, 9, 10)
puts Time.utc(2008, 7, 8, 9, 10)

时间格式化

puts time1.strftime('%Y-%m-%d %H:%M:%S')

字符串转为时间

字符串需符合此格式

puts Time.parse('2014-04-23').inspect

时间计算

puts time2 - 10 # 10 seconds ago
沪ICP备17055033号-2