ruby - 时间处理

发表于:,更新于:,By Sally
大纲
  1. 1. 创建时间实例
  2. 2. 时间戳 & 年月日
  3. 3. 时间判断
  4. 4. 时间计算

创建时间实例

  • Time.new(year, month, day, hour, min, sec, usec_with_frac)
1
2
3
4
5
6
Time.new  =>  2016-07-05 14:41:25 +0800
Time.new(2016) => 2016-01-01 00:00:00 +0800
Time.new(2016, 10) => 2016-10-01 00:00:00 +0800
Time.new(2016, 10, 3) => 2016-10-03 00:00:00 +0800
Time.new(2016, 10, 3, 5, 6, 7) => 2016-10-03 05:06:07 +0800
Time.new(2016, 10, 3, 5, 6, 7, "=03:00") => 2016-10-03 05:06:07 +0300

时间戳 & 年月日

1
2
3
a = Time.new => 2016-07-05 14:49:11 +0800
a.to_i => 1467701351
Time.at(1467701351) => 2016-07-05 14:49:11 +0800
  • 生成&解析13位的unix时间戳 参考文档ri strptime
1
2
3
4
require 'date'
a = Time.new => 2016-07-05 14:49:11 +0800
a.to_datetime.strftime '%Q' => "1467701351000"
DateTime.strptime('1467701351000', '%Q').strftime('%Y-%m-%d %H:%M:%S') => "2016-07-05 06:49:11"

时间判断

1
2
3
4
5
6
7
8
9
10
11
t = Time.new(2016, 7, 5, 16, 15, 17) => 2016-07-05 16:15:17 +0800
t.monday? => false
t.tuesday? => true
t.year => 2016

t1 = Time.new(2016, 8, 5)
t1 > t => true

t2 = Time.new(2015, 8, 5)
t.between?(t2, t1)? => true
t.between?(t1, t2)? => false

时间计算

  • time - other_time #=> float(秒值)
  • time - numeric #=> time
1
2
3
4
t1 = Time.new(2015, 8, 5) #=> 2015-08-05 00:00:00 +0800
t2 = Time.new(2016, 9, 10)
des = t2 - t1 #=> 34732800.0
t1 + 360 #=> 2015-08-05 00:06:00 +0800