Ruby中时间

1. 基础

time = Time.new
time = Time.now
time.year     # => Year of the date
time.month    # => Month of the date (1 to 12)
time.day      # =>Day of the date (1 to 31)
time.wday     # => Day of week: (0 to 6) 0 is Sunday
time.yday     # => (0 to 365) Day of year
time.hour     # => (0 to 23)

2. 格式化产生时间

time = Time.new(2008, 7, 8)           # 2008-07-08 00:00:00 +0800
time = Time.local(2008, 7, 8)         # 2008-07-08 00:00:00 +0800
time = Time.local(2008, 7, 8, 9, 10)  # 2008-07-08 09:10:00 +0800
time = Time.utc(2008, 7, 8)           #2008-07-08 00:00:00 UTC
time = Time.gm(2008, 7, 8)

3.格式转化

#转化为数组
time_arr = time.to_a
#[sec,min,hour,day,month,year,wday,yday,isdst,zone]
#这个数组可以传给Time.utc或者Time.local函数
v = Time.utc(*time_arr)

#格式化
time.to_s
time.ctime
time.localtime
time.strftime("%Y-%m-%d %H:%M:%S")

now = Time.now
past = now - 10 #10 seconds ago
#下面的在rails中可以使用
#past = now.to_date - 10.months

4. rails 中对时间的扩展

class Integer
  def months
    ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
  end
  alias :month :months

  def years
    ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
  end
  alias :year :years
end

字符串转化为时间

DateTime.parse('20120514144424').strftime('%Y-%m-%d %H:%M:%S')
"20120514144424".to_time.strftime('%Y-%m-%d %H:%M:%S')
"20120514144424".to_datetime.strftime('%Y-%m-%d %H:%M:%S')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容