day = Time.now (或Time.new) p day.to_s #=> "Sun May 20 23:48:45 JST 2008" p day.year #=> 2008 p day.month #=> 5 p day.day #=> 20 p day.hour #=> 23 p day.min #=> 48 p day.sec #=> 45 p day.wday #=> 0 |
使用Time.gm类生成GMT时区时间
day = Time.gm(2008, 5, 20, 23, 59, 59) #=> Sun May 20 23:59:59 UTC 2008 day = Time.local(2008, 5, 20, 23, 59, 59) #=> Sun May 20 23:59:59 JST 2008 |
strftime方法中任意时刻的格式化符号
%A: 星期的名称(如:Sunday, Monday ... )
%a: 星期的名称缩写(如:Sun, Mon ... )
%B: 月份的名称(如:January, February ... )
%b: 月份的名称缩写(如:Jan, Feb ... )
%c: 日期,时刻
%d: 日(01-31)
%H: 24小时制的时间(00-23)
%I: 12小时制的时间(01-12)
%j: 一年中的通算日(001-366)
%M: 分(00-59)
%m: 月(01-12)
%p: 午前和午后(AM,PM)
%S: 秒(00-60)
%w: 一周的天数,周日(0)开始算起(0-6)
%X: 时刻
%x: 日期
%Y: 阳历
%Z: 时区
day = Time.now p day.strftime("Now, %A %B %d %X %Z %Y") #=> "Now, Sunday May 20 23:33:37 JST 2008" |
时刻的加减
day = Time.local(2008, 5, 20, 23, 59, 59) #=> Sun May 20 23:59:59 JST 2008 day = day + 1 #=> Mon May 21 00:00:00 JST 2008 day = Time.local(2000, 12, 31, 0, 0, 0) #=> Sun Dec 31 00:00:00 JST 2000 day = day + 24*60*60 #=> Mon Jan 01 00:00:00 JST 2008 |
时刻的求时差
day1 = Time.local(2007, 12, 31, 0, 0, 0) #=> Sun Dec 31 00:00:00 JST 2007 day2 = Time.local(2008, 1, 2, 12, 30, 0) #=> Tue Jan 02 12:30:00 JST 2008 days = (day2 - day1).divmod(24*60*60) #=> [2.0, 45000.0] hours = days[1].divmod(60*60) #=> [12.0, 1800.0] mins = hours[1].divmod(60) #=> [30.0, 0.0] |
当前日期
require 'date' day = Date::new(2008, 5, 31) p day.to_s #=> "2008-05-31" |
昨天,前天
require 'date' day = Date.new(2008, 5, 31) day = day + 1 p day.to_s #=> "2008-06-01" day = Date.new(2008, 1, 1) day = day - 1 p day.to_s #=> "2007-12-31" |
下月,上月
require 'date' day = Date.new(2008, 1, 31) day = day >> 1 p day.to_s #=> "2008-2-28" day = Date.new(2008, 5, 31) day = day << 1 p day.to_s #=> "2008-04-30" |
闰年
require 'date' day = Date.new(2000) p day.leap? #=> true day = Date.new(2001) p day.leap? #=> false |
日期的格式化
require 'date' day = Date::new(2008, 1, 31) p day.year #=> 2008 p day.month #=> 1 p day.day #=> 31 p day.wday #=> 3 |
没有评论:
发表评论