美文网首页
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中时间

    1. 基础 2. 格式化产生时间 3.格式转化 4. rails 中对时间的扩展 字符串转化为时间

  • Ruby安装(Mac)

    Ruby安装 ruby-install 和 chruby 管理 Ruby ruby-install能在任意目录中编...

  • Effective Ruby

    一、 让自己熟悉Ruby 1、理解 Ruby 中的 True 在 Ruby 中,除了 false 和 nil, 其...

  • CentOS 7 配置Ruby语言开发环境

    CentOS 7 配置Ruby语言开发环境 Ruby环境 安装Ruby 2.2 CentOS7存储库中的Ruby版...

  • iOS Mac安装CocoaPods

    1、查看ruby版本,在终端中输入ruby -v,2.0版本过低,需要升级ruby 2、升级ruby 1)检查是否...

  • Mac安装CocoaPods教程.

    安装Ruby环境 查看Mac是否安装Ruby和gem 在终端中输入命令:ruby --version 和gem -...

  • iOS Cocoapods 只看我就够了

    Xcode已经默认安装好Ruby环境,如果你不确定自己系统中是否有Ruby的,可以在终端中输入命令行:$ ruby...

  • 整理Cocoapods安装

    一、检查环境 cocoapods安装需要ruby环境,Mac默认自带ruby环境,可以在终端中输入:ruby -v...

  • RubyGems、Gem、Bundle

    类比于C#中的包,Java中的package,Ruby程序中的代码库( ruby software package...

  • Ruby中的Module

    Ruby中没有Java语言中的interface,Ruby只支持单继承。Ruby通过Mix-in提供对类的扩展,其...

网友评论

      本文标题:Ruby中时间

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