Rails时间方法操作

to_s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>> now.to_s
=> "Sat Jan 29 21:47:07 +0800 2011"
>> now.to_s(:db)
=> "2011-01-29 21:47:07"
>> now.to_s(:number)
=> "20110129214707"
>> now.to_s(:time)
=> "21:47"
>> now.to_s(:short)
=> "29 Jan 21:47"
>> now.to_s(:long)
=> "January 29, 2011 21:47"
>> now.to_s(:long_ordinal)
=> "January 29th, 2011 21:47"
>> now.to_s(:rfc822)
=> "Sat, 29 Jan 2011 21:47:07 +0800"
begginning
1
2
3
4
5
6
7
8
9
10
11
12
>> now.beginning_of_day
=> Sat Jan 29 00:00:00 0800 2011
>> now.midnight
=> Sat Jan 29 00:00:00 0800 2011
>> now.beginning_of_week
=> Mon Jan 24 00:00:00 0800 2011
>> now.beginning_of_month
=> Sat Jan 01 00:00:00 0800 2011
>> now.beginning_of_quarter
=> Sat Jan 01 00:00:00 0800 2011
>> now.beginning_of_year
=> Sat Jan 01 00:00:00 0800 2011
end
1
2
3
4
5
6
7
8
9
10
>> now.end_of_day
=> Sat Jan 29 23:59:59 0800 2011
>> now.end_of_week
=> Sun Jan 30 23:59:59 0800 2011
>> now.end_of_month
=> Mon Jan 31 23:59:59 0800 2011
>> now.end_of_quarter
=> Thu Mar 31 23:59:59 0800 2011
>> now.end_of_year
=> Sat Dec 31 23:59:59 0800 2011
时间的魔术方法
1
2
3
4
5
6
7
8
9
>> now.yesterday
=> Fri Jan 28 21:47:07 0800 2011
>> now.tomorrow
=> Sun Jan 30 21:47:07 0800 2011
>> now.next_week
=> Mon Jan 31 00:00:00 0800 2011
>> now.next_month
=> Mon Feb 28 21:47:07 0800 2011
>> now.next_year
prev_week
1
2
3
4
>> now.prev_month
=> Wed Dec 29 21:47:07 0800 2010
>> now.prev_year
=> Fri Jan 29 21:47:07 0800 2010
今日已过秒数
1
2
>> now.seconds_since_midnight
=> 78427.615017
日期输出
1
2
3
4
>> now.to_date
=> Sat, 29 Jan 2011
>> now.to_datetime
=> Sat, 29 Jan 2011 21:47:07 0800
按秒数计算
1
2
3
4
>> now.ago(3600)
=> Sat Jan 29 20:47:07 0800 2011
>> now.since(3600)
=> Sat Jan 29 22:47:07 0800 2011
时间差计算
1
2
3
4
5
6
5.months.since(Time.parse('1999-12-01'))
 => 2000-05-01 00:00:00 +0800


5.months.ago(Time.parse('1999-12-01'))
 => 1999-07-01 00:00:00 +0800

如果要自己设计时间输出格式,按下面方法来,新建一个配置文件

config/initializers/time_formats.rb
1
2
  Time::DATE_FORMATS[:month_and_year] = "%B %Y"
  Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
时间格化输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
%a - 星期几的英文简写 (``Sun'')
%A - 星期几的英文全称 (``Sunday'')
%b - 月份的英文简写 (``Jan'')
%B - 月份的英文全称 (``January'')
%c - 默认的首选本地时间输出格式
%d - 本月第几天 (01..31)
%H - 24小时制的小时 (00..23)
%I - 12小时制的小时 (01..12)
%j - 今年的第几天 (001..366)
%m - 月份 (01..12)
%M - 分钟 (00..59)
%p - 上午还是下午 (``AM''  or  ``PM'')
%S - 秒数 (00..60)
%U - 从星期天算一周开始的本年第几周 (00..53)
%W - 从星期一算一周开始的本年第几周 (00..53)
%w - 现在是星期几 (周日是0 , 0..6)
%x - 默认的日期输出格式 ("01/29/11")
%X - 默认的时间输出格式 ("21:47:07")
%y - 年份的后两位 (00..99)
%Y - 年份
%Z - 时区名
%% - 输出%字符

>> now.strftime("%Y-%m-%d %H:%M:%S")
=> "2011-01-29 21:47:07"

待补充更新…

原文地址:http://dlj.bz/PvlKDw

Comments