Time类
更新: 2017/06/23 更新了Data/Time在model模式下的便利方法
更新: 2018/10/12 修改了%Y相关描述防止误解
| 年月日时分秒,时区 |
|
| 生成 |
| 获取当前时间 |
Time.new()
Time.now() |
| 生成 |
Time.mktime(2017, 5, 22, 0, 15, 15)
年,月,日,时,分,秒,微秒
可省略除年以外的参数 |
| 经过时间 |
Time.at(12345)
单位:秒
起点:1970/01/01/0/0/0 |
| |
|
| |
|
|
| 获取属性的值 |
t = Time.new()
| t.year |
年 |
| t.month |
月 |
| t.day |
日 |
| t.hour |
小时 |
| t.min |
分 |
| t.sec |
秒 |
| t.usec |
秒以下的量
微秒单位 |
| t.nsec |
秒以下的量
纳秒 |
| t.to.i |
1970年1月1日0秒
开始经过的秒数 |
| t.wday |
本周第几天
周日为0 |
| t.mday |
本月第几日
|
| t.yday |
一年的第几天
第一天为1 |
| t.zone |
时区 |
| t.utc_offset |
与标准时的时差
单位为秒 |
| |
|
|
| 比较 |
t1 = Time.new()
t2 = Time.mktime(2018, 1, 1) |
| 输出 |
t.to_s()
t.strftime(format)
| format |
字符串 |
| %A |
星期
Sunday... |
| %a |
星期简称
Sun, Mon, ... |
| %B |
月
January, ... |
| %b |
月简称
Jan, Feb, ... |
| %c |
Wed Jun 21 02:11:47 2017
|
| %d |
日(01~31) |
| %H |
时
24小时制 |
| %I |
时
12小时制 |
| %j |
一年的第几天
001~366 |
| %M |
分 00~59 |
| %m |
月 01~12 |
| %p |
上下午 AM,PM |
| %S |
秒 00~60 |
| %U |
周 星期天为起点 |
| %W |
周 星期一为起点 |
| %w |
星期几 0~6
周日为0 |
| %X |
时间 |
| %x |
日期 |
| %Y |
阳历年 2017 |
| %y |
阳历年后两位 00~99 |
| %Z |
时区 JST
和电脑本地时区一致 |
| %z |
时区 +900 |
| %% |
% |
| |
|
| |
|
| |
|
|
| 转换 |
t.uct() 这个会改变本身
t.getutc() |
转换为标准时 |
t.localtime()
t.getlocal() |
转换为本地时区时 |
| t.to_date() |
转为日期 |
| d.to_time() |
转为时间 |
| |
|
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| time库 |
require "time" |
| 邮件日期格式 |
t.rfc2822()
Request For Comments 的RFC2822而来
Mon, 22 May 2017 02:39:13 +0900
|
| 国际标准表示 |
t.iso8601()
2017-05-22T02:39:13+09:00 |
| 文字转日期 |
Time.parse("2017/1/1")
2017-01-01 00:00:00 +0900 |
对应大部分情况 |
| Time.strptime(str, format) |
自定义配对的格式 |
| |
|
| |
|
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
Date类
| 年月日 |
|
| require "date" |
|
| 生成 |
| Date.today() |
获取今日 |
Date.new(2015, 1, 1)
月末一天 -1
倒数第二天 -2 |
指定日期 |
| |
|
| |
|
| |
|
|
| 运算 |
| 减法 |
获取天数
结果是有理数Rational(...) |
加法
只加数字 |
获取过后的日期 |
| >> n |
到n月后的同一天
超过范围就最后 |
| << n |
到n月前的同一天 |
|
| 输出 |
t.to_s()
t.strftime("%Y/%m/%d")
|
| 转换 |
Time.parse("2017/1/1")
2017-01-01 00:00:00 +0900 |
对应大部分情况 |
| Time.strptime(str, format) |
自定义配对的格式 |
| t.to_date() |
转为日期 |
| d.to_time() |
转为时间 |
|
| |
|
| |
|
| |
|
| |
|
|
Data/Time相关的有用的方法 |
| yesterday |
昨天 |
| tomorrow |
明天 |
| prev_xxxx |
前年/月/周(year,month,week) |
| next_xxxx |
下年/月/周(year,month,week) |
| beginning_of_xxxx |
年/季/月/周的开始一天(year, quarter, month, day) |
| end_of_xxxx |
年/季/月/周的最后一条(year, quarter, month, day) |
| |
|
n.xxx.ago
Numeric |
n个年/月/日/时/分/秒以前
years, months, days, hours, minutes, seconds
也可以用单数 |
n.xxx.from_now
Numeric |
n个年/月/日/时/分/秒以后
years, months, days, hours, minutes, seconds
也可以用单数 |