美文网首页
Ruby中时间

Ruby中时间

作者: yaya_pangdun | 来源:发表于2016-06-15 11:11 被阅读71次

    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')
    

    相关文章

      网友评论

          本文标题:Ruby中时间

          本文链接:https://www.haomeiwen.com/subject/woetrttx.html