首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Time

Parent:ObjectIncluded modules:Comparable

当需要'time'时,时间通过附加的解析和转换时间的方法进行扩展。

特征

该库使用日期字符串和时间对象之间的以下转换扩展了Time类:

  • 由XML Schema第2部分定义的dateTime:数据类型(ISO 8601
  • 由Date._parse处理各种格式
  • 由Date._strptime处理的自定义格式

示例

所有示例假定您已将Time加载到:

代码语言:javascript
复制
require 'time'

所有这些例子都是使用GMT-5的EST时区完成的。

转换为字符串

代码语言:javascript
复制
t = Time.now
t.iso8601  # => "2011-10-05T22:26:12-04:00"
t.rfc2822  # => "Wed, 05 Oct 2011 22:26:12 -0400"
t.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"

::parse

解析需要一个时间的字符串表示,并尝试使用启发式来解析。

代码语言:javascript
复制
Time.parse("2010-10-31") #=> 2010-10-31 00:00:00 -0500

根据当前日期推断任何缺失的日期片段。

代码语言:javascript
复制
# assuming the current date is "2011-10-31"
Time.parse("12:00") #=> 2011-10-31 12:00:00 -0500

我们可以通过传递第二个响应mon,day和year的对象(如Date,Time或DateTime)来更改用于推断缺失元素的日期。我们也可以使用我们自己的对象。

代码语言:javascript
复制
class MyDate
  attr_reader :mon, :day, :year

  def initialize(mon, day, year)
    @mon, @day, @year = mon, day, year
  end
end

d  = Date.parse("2010-10-28")
t  = Time.parse("2010-10-29")
dt = DateTime.parse("2010-10-30")
md = MyDate.new(10,31,2010)

Time.parse("12:00", d)  #=> 2010-10-28 12:00:00 -0500
Time.parse("12:00", t)  #=> 2010-10-29 12:00:00 -0500
Time.parse("12:00", dt) #=> 2010-10-30 12:00:00 -0500
Time.parse("12:00", md) #=> 2010-10-31 12:00:00 -0500

解析也接受一个可选块。您可以使用此块指定如何处理日期的年份部分。这是专门为处理两位数年份而设计的。例如,如果你想在2000年之前把70年前的所有两位数字年对待,你可以写下这样的话:

代码语言:javascript
复制
Time.parse("01-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
#=> 2001-10-31 00:00:00 -0500
Time.parse("70-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
#=> 1970-10-31 00:00:00 -0500

::strptime

strptime的工作方式类似,parse除了使用启发式来检测输入字符串的格式,您提供了第二个参数来描述字符串的格式。例如:

代码语言:javascript
复制
Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500

时间是日期和时间的抽象。时间在内部存储为秒分数,因为数时代,1970年1月1日00:00 UTC。另请参阅库模块Date。Time类将GMT(格林威治标准时间)和UTC(协调世界时)视为等同。GMT是引用这些基准时间的较早方式,但仍然存在于POSIX系统上的调用名称中。

所有时间可能都有分数。当比较彼此时间时要注意这一事实 - 在显示时显然相同的时间在比较时可能不同。

从Ruby 1.9.2开始,Time实现使用带符号的63位整数Bignum或Rational。整数是从Epoch开始的纳秒数,它可以表示1823-11-12到2116-02-20。当使用Bignum或Rational(1823年之前,2116之后,纳秒)时,Time与使用整数时相比运行速度更慢。

所有这些例子都是使用GMT-5的EST时区完成的。

创建一个新的时间实例

您可以使用::new创建一个新的Time实例。这将使用当前的系统时间。::现在是这个的别名。您也可以将部分时间传递给::new,如年,月,分等。如果您想以这种方式构建时间,您必须至少通过一年。如果你没有其他时间通过这一年,那么当前系统时区将在00:00:00的默认时间为1月1日。这里有些例子:

代码语言:javascript
复制
Time.new(2002)         #=> 2002-01-01 00:00:00 -0500
Time.new(2002, 10)     #=> 2002-10-01 00:00:00 -0500
Time.new(2002, 10, 31) #=> 2002-10-31 00:00:00 -0500
Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200

您也可以使用gm,local和utc来推断GMT,本地和UTC时区,而不是使用当前的系统设置。

你还可以使用::at创建一个新的时间,这个时间从Unix Epoch开始的秒数(或小数秒)。

代码语言:javascript
复制
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500

使用Time的实例

一旦你有一个时间实例,你可以用它做很多事情。以下是一些例子。对于以下所有示例,我们将假设您已完成以下工作:

代码语言:javascript
复制
t = Time.new(1993, 02, 24, 12, 0, 0, "+09:00")

Was that a monday?

代码语言:javascript
复制
t.monday? #=> false

What year was that again?

代码语言:javascript
复制
t.year #=> 1993

Was it daylight savings at the time?

代码语言:javascript
复制
t.dst? #=> false

What's the day a year later?

代码语言:javascript
复制
t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900

How many seconds was that since the Unix Epoch?

代码语言:javascript
复制
t.to_i #=> 730522800

You can also do standard functions like compare two times.

代码语言:javascript
复制
t1 = Time.new(2010)
t2 = Time.new(2011)

t1 == t2 #=> false
t1 == t1 #=> true
t1 <  t2 #=> true
t1 >  t2 #=> false

Time.new(2010,10,31).between?(t1, t2) #=> true

公共类别方法

at(time) → time Show source

at(seconds_with_frac) → time

at(seconds, microseconds_with_frac) → time

创建与给定的值一个新的时间对象time,给定数量的seconds_with_frac,或secondsmicroseconds_with_frac自纪元。seconds_with_frac并且microseconds_with_frac可以是Integer,Float,Rational或其他数字。非便携式功能允许某些系统上的偏移量为负值。

如果给出数字参数,则结果是在本地时间。

代码语言:javascript
复制
Time.at(0)                           #=> 1969-12-31 18:00:00 -0600
Time.at(Time.at(0))                  #=> 1969-12-31 18:00:00 -0600
Time.at(946702800)                   #=> 1999-12-31 23:00:00 -0600
Time.at(-284061600)                  #=> 1960-12-31 00:00:00 -0600
Time.at(946684800.2).usec            #=> 200000
Time.at(946684800, 123456.789).nsec  #=> 123456789
代码语言:javascript
复制
static VALUE
time_s_at(int argc, VALUE *argv, VALUE klass)
{
    VALUE time, t;
    wideval_t timew;

    if (rb_scan_args(argc, argv, "11", &time, &t) == 2) {
        time = num_exact(time);
        t = num_exact(t);
        timew = wadd(rb_time_magnify(v2w(time)), wmulquoll(v2w(t), TIME_SCALE, 1000000));
        t = time_new_timew(klass, timew);
    }
    else if (IsTimeval(time)) {
        struct time_object *tobj, *tobj2;
        GetTimeval(time, tobj);
        t = time_new_timew(klass, tobj->timew);
        GetTimeval(t, tobj2);
        TIME_COPY_GMT(tobj2, tobj);
    }
    else {
        timew = rb_time_magnify(v2w(num_exact(time)));
        t = time_new_timew(klass, timew);
    }

    return t;
}

gm(year) → time Show source

gm(year, month) → time

gm(year, month, day) → time

gm(year, month, day, hour) → time

gm(year, month, day, hour, min) → time

gm(year, month, day, hour, min, sec_with_frac) → time

gm(year, month, day, hour, min, sec, usec_with_frac) → time

gm(sec, min, hour, day, month, year, dummy, dummy, dummy, dummy) → time

根据给定值创建Time对象,解释为UTC(GMT)。年份必须指定。其他值默认为该字段的最小值(可以是nil或可以省略)。月份可能由1到12的数字或3个字母的英文月份名称指定。小时在24小时制(0..23)上指定。如果任何值超出范围,则引发参数错误。还将接受#to_a输出的顺序中的十个参数。

sec_with_fracusec_with_frac可以有一个小数部分。

代码语言:javascript
复制
Time.utc(2000,"jan",1,20,15,1)  #=> 2000-01-01 20:15:01 UTC
Time.gm(2000,"jan",1,20,15,1)   #=> 2000-01-01 20:15:01 UTC
代码语言:javascript
复制
static VALUE
time_s_mkutc(int argc, VALUE *argv, VALUE klass)
{
    return time_utc_or_local(argc, argv, TRUE, klass);
}

httpdate(date) Show source

解析date为RFC 2616定义的HTTP日期,并将其转换为Time对象。

如果date不符合RFC 2616或者Time类不能表示指定的日期,则引发ArgumentError 。

有关此格式的更多信息,请参阅httpdate。

你必须要求'time'来使用这种方法。

代码语言:javascript
复制
# File lib/time.rb, line 522
def httpdate(date)
  if /\A\s*
      (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
      (\d{2})\x20
      (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
      (\d{4})\x20
      (\d{2}):(\d{2}):(\d{2})\x20
      GMT
      \s*\z/ix =~ date
    self.rfc2822(date).utc
  elsif /\A\s*
         (?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
         (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
         (\d\d):(\d\d):(\d\d)\x20
         GMT
         \s*\z/ix =~ date
    year = $3.to_i
    if year < 50
      year += 2000
    else
      year += 1900
    end
    self.utc(year, $2, $1.to_i, $4.to_i, $5.to_i, $6.to_i)
  elsif /\A\s*
         (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
         (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
         (\d\d|\x20\d)\x20
         (\d\d):(\d\d):(\d\d)\x20
         (\d{4})
         \s*\z/ix =~ date
    self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
             $3.to_i, $4.to_i, $5.to_i)
  else
    raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
  end
end

iso8601(date)

别名为:xmlschema

json_create(object) Show source

通过将时间自时代转换为时间来反序列化JSON字符串

代码语言:javascript
复制
# File ext/json/lib/json/add/time.rb, line 9
def self.json_create(object)
  if usec = object.delete('u') # used to be tv_usec -> tv_nsec
    object['n'] = usec * 1000
  end
  if method_defined?(:tv_nsec)
    at(object['s'], Rational(object['n'], 1000))
  else
    at(object['s'], object['n'] / 1000)
  end
end

local(year) → time Show source

local(year, month) → time

local(year, month, day) → time

local(year, month, day, hour) → time

local(year, month, day, hour, min) → time

local(year, month, day, hour, min, sec_with_frac) → time

local(year, month, day, hour, min, sec, usec_with_frac) → time

local(sec, min, hour, day, month, year, dummy, dummy, isdst, dummy) → time

Same as ::gm, but interprets the values in the local time zone.

代码语言:javascript
复制
Time.local(2000,"jan",1,20,15,1)   #=> 2000-01-01 20:15:01 -0600
代码语言:javascript
复制
static VALUE
time_s_mktime(int argc, VALUE *argv, VALUE klass)
{
    return time_utc_or_local(argc, argv, FALSE, klass);
}

mktime(year) → time Show source

mktime(year, month) → time

mktime(year, month, day) → time

mktime(year, month, day, hour) → time

mktime(year, month, day, hour, min) → time

mktime(year, month, day, hour, min, sec_with_frac) → time

mktime(year, month, day, hour, min, sec, usec_with_frac) → time

mktime(sec, min, hour, day, month, year, dummy, dummy, isdst, dummy) → time

与::gm相同,但解释本地时区中的值。

代码语言:javascript
复制
Time.local(2000,"jan",1,20,15,1)   #=> 2000-01-01 20:15:01 -0600
代码语言:javascript
复制
static VALUE
time_s_mktime(int argc, VALUE *argv, VALUE klass)
{
    return time_utc_or_local(argc, argv, FALSE, klass);
}

new → time Show source

new(year, month=nil, day=nil, hour=nil, min=nil, sec=nil, utc_offset=nil) → time

Returns a Time object.

如果没有给出参数,它将被初始化为当前系统时间。

注意:新对象将使用系统时钟上可用的分辨率,并可能包含小数秒。

如果指定了一个或多个参数,则时间将初始化为指定的时间。

sec 如果它是理性的,可能会有分数。

utc_offset是UTC的偏移量。它可以是诸如“+09:00”之类的字符串或诸如32400之类的秒数。

代码语言:javascript
复制
a = Time.new      #=> 2007-11-19 07:50:02 -0600
b = Time.new      #=> 2007-11-19 07:50:02 -0600
a == b            #=> false
"%.6f" % a.to_f   #=> "1195480202.282373"
"%.6f" % b.to_f   #=> "1195480202.283415"

Time.new(2008,6,21, 13,30,0, "+09:00") #=> 2008-06-21 13:30:00 +0900

# A trip for RubyConf 2007
t1 = Time.new(2007,11,1,15,25,0, "+09:00") # JST (Narita)
t2 = Time.new(2007,11,1,12, 5,0, "-05:00") # CDT (Minneapolis)
t3 = Time.new(2007,11,1,13,25,0, "-05:00") # CDT (Minneapolis)
t4 = Time.new(2007,11,1,16,53,0, "-04:00") # EDT (Charlotte)
t5 = Time.new(2007,11,5, 9,24,0, "-05:00") # EST (Charlotte)
t6 = Time.new(2007,11,5,11,21,0, "-05:00") # EST (Detroit)
t7 = Time.new(2007,11,5,13,45,0, "-05:00") # EST (Detroit)
t8 = Time.new(2007,11,6,17,10,0, "+09:00") # JST (Narita)
p((t2-t1)/3600.0)                          #=> 10.666666666666666
p((t4-t3)/3600.0)                          #=> 2.466666666666667
p((t6-t5)/3600.0)                          #=> 1.95
p((t8-t7)/3600.0)                          #=> 13.416666666666666
代码语言:javascript
复制
static VALUE
time_init(int argc, VALUE *argv, VALUE time)
{
    if (argc == 0)
        return time_init_0(time);
    else
        return time_init_1(argc, argv, time);
}

now → time Show source

为当前时间创建一个新的时间对象。这与不带参数的new相同。

代码语言:javascript
复制
Time.now            #=> 2009-06-24 12:39:54 +0900
代码语言:javascript
复制
static VALUE
time_s_now(VALUE klass)
{
    return rb_class_new_instance(0, NULL, klass);
}

parse(date, now=self.now) { |year| ... } Show source

date使用Date._parse 解析并将其转换为Time对象。

如果给出了一个块,那么所描述的年份将date被该块转换。例如:

代码语言:javascript
复制
Time.parse(...) {|y| 0 <= y && y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}

如果给定时间的上层组件被破坏或丢失,那么它们将被提供now。对于较低的组件,如果损坏或丢失,则假定最小值(1或0)。例如:

代码语言:javascript
复制
# Suppose it is "Thu Nov 29 14:33:20 2001" now and
# your time zone is EST which is GMT-5.
now = Time.parse("Thu Nov 29 14:33:20 2001")
Time.parse("16:30", now)     #=> 2001-11-29 16:30:00 -0500
Time.parse("7/23", now)      #=> 2001-07-23 00:00:00 -0500
Time.parse("Aug 31", now)    #=> 2001-08-31 00:00:00 -0500
Time.parse("Aug 2000", now)  #=> 2000-08-01 00:00:00 -0500

由于世界各地在本地定义的时区缩写之间存在许多冲突,因此此方法无意理解所有这些缩写。例如,缩写“CST”被不同地用作:

代码语言:javascript
复制
-06:00 in America/Chicago,
-05:00 in America/Havana,
+08:00 in Asia/Harbin,
+09:30 in Australia/Darwin,
+10:30 in Australia/Adelaide,
etc.

基于这一事实,此方法仅按照RFC 822中描述的时区缩写和系统时区,按命名顺序。(即RFC 822中的定义覆盖系统时区定义。)系统时区取自Time.local(year, 1, 1).zoneTime.local(year, 7, 1).zone。如果提取的时区缩写与它们中的任何一个不匹配,则忽略它并将给定时间视为当地时间。

如果Date._parse无法从中提取信息,date或者Time类无法表示指定日期,则会引发ArgumentError 。

此方法可用作其他解析方法的故障安全,如下所示:

代码语言:javascript
复制
Time.rfc2822(date) rescue Time.parse(date)
Time.httpdate(date) rescue Time.parse(date)
Time.xmlschema(date) rescue Time.parse(date)

但是,应该检查::parse的失败。

你必须要求'time'来使用这种方法。

代码语言:javascript
复制
# File lib/time.rb, line 364
def parse(date, now=self.now)
  comp = !block_given?
  d = Date._parse(date, comp)
  year = d[:year]
  year = yield(year) if year && !comp
  make_time(date, year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
end

rfc2822(date) Show source

date按照RFC 2822定义的日期时间解析并将其转换为Time对象。格式与RFC 822定义的日期格式相同,并由RFC 1123更新。

如果date不符合RFC 2822或者Time类不能表示指定的日期,则引发ArgumentError 。

有关此格式的更多信息,请参阅rfc2822。

你必须要求'time'来使用这种方法。

代码语言:javascript
复制
# File lib/time.rb, line 469
def rfc2822(date)
  if /\A\s*
      (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
      (\d{1,2})\s+
      (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
      (\d{2,})\s+
      (\d{2})\s*
      :\s*(\d{2})\s*
      (?::\s*(\d{2}))?\s+
      ([+-]\d{4}|
       UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
    # Since RFC 2822 permit comments, the regexp has no right anchor.
    day = $1.to_i
    mon = MonthValue[$2.upcase]
    year = $3.to_i
    short_year_p = $3.length <= 3
    hour = $4.to_i
    min = $5.to_i
    sec = $6 ? $6.to_i : 0
    zone = $7

    if short_year_p
      # following year completion is compliant with RFC 2822.
      year = if year < 50
               2000 + year
             else
               1900 + year
             end
    end

    off = zone_offset(zone)
    year, mon, day, hour, min, sec =
      apply_offset(year, mon, day, hour, min, sec, off)
    t = self.utc(year, mon, day, hour, min, sec)
    force_zone!(t, zone, off)
    t
  else
    raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
  end
end

另外别名为:rfc822

rfc822(date)

别名为:rfc2822

strptime(date, format, now=self.now) { |year| ... } Show source

date使用Date._strptime 解析并将其转换为Time对象。

如果给出了一个块,那么所描述的年份将date被该块转换。例如:

代码语言:javascript
复制
Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}

以下是格式选项的列表:

%a

缩写周日名称(“Sun”)

%A

完整的星期几名称(“Sunday”)

%b

缩写月份名称(“Jan”)

%B

完整的月份名称(“January”)

%c

首选的本地日期和时间表示

%C

Century (20 in 2009)

%d

Day of the month (01..31)

%D

Date (%m/%d/%y)

%e

Day of the month, blank-padded ( 1..31)

%F

等同于%Y-%m-%d(ISO 8601日期格式)

%h

相当于%b

%H

当天的小时,24小时制(00..23)

%I

当天的小时,12小时制(01..12)

%j

年的一天(001..366)

%k

小时,24小时制,空白填充(0..23)

%l

小时,12小时制,空白填充(0..12)

%L

第二秒的毫秒(000..999)

%m

一年中的月份(01..12)

%M

小时(00..59)

%n

Newline (n)

%N

小数秒位数,默认值是9位数(纳秒)

%3N

millisecond (3 digits)

%6N

microsecond (6 digits)

%9N

nanosecond (9 digits)

代码语言:txt
复制
%p   

子午指示符(“AM”或“PM”)

%P

子午指示符(“am”或“pm”)

%r

time, 12-hour (same as %I:%M:%S %p)

%R

time, 24-hour (%H:%M)

%s

自1970-01-01 00:00:00 UTC以来的秒数。

%S

第二分钟(00..60)

%t

制表符(t)

%T

time, 24-hour (%H:%M:%S)

%u

星期几为小数,星期一为1.(1..7)

%U

当年的周数,从第一个星期的第一周开始(00..53)

%v

VMS date (%e-%b-%Y)

%V

根据ISO 8601(01..53)的年数

%W

当年的周数,从第一个星期一开始,作为第一周的第一天(00..53)

%w

星期几(星期日是0,0..6)

%x

仅限日期的优先表示,没有时间

%X

单独的时间的优先表示,没有日期

%y

没有世纪的一年(00..99)

%Y

如果提供,可能包括世纪的年份

%z

Time zone as hour offset from UTC (e.g. +0900)

%Z

Time zone name

%%

Literal “%” character

代码语言:javascript
复制
# File lib/time.rb, line 430
def strptime(date, format, now=self.now)
  d = Date._strptime(date, format)
  raise ArgumentError, "invalid strptime format - `#{format}'" unless d
  if seconds = d[:seconds]
    if sec_fraction = d[:sec_fraction]
      usec = sec_fraction * 1000000
      usec *= -1 if seconds < 0
    else
      usec = 0
    end
    t = Time.at(seconds, usec)
    if zone = d[:zone]
      force_zone!(t, zone)
    end
  else
    year = d[:year]
    year = yield(year) if year && block_given?
    t = make_time(date, year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
  end
  t
end

utc(year) → time Show source

utc(year, month) → time

utc(year, month, day) → time

utc(year, month, day, hour) → time

utc(year, month, day, hour, min) → time

utc(year, month, day, hour, min, sec_with_frac) → time

utc(year, month, day, hour, min, sec, usec_with_frac) → time

utc(sec, min, hour, day, month, year, dummy, dummy, dummy, dummy) → time

根据给定值创建Time对象,解释为UTC(GMT)。年份必须指定。其他值默认为该字段的最小值(可以是nil或可以省略)。月份可能由1到12的数字或3个字母的英文月份名称指定。小时在24小时制(0..23)上指定。如果任何值超出范围,则引发参数错误。还将接受#to_a输出的顺序中的十个参数。

sec_with_fracusec_with_frac可以有一个小数部分。

代码语言:javascript
复制
Time.utc(2000,"jan",1,20,15,1)  #=> 2000-01-01 20:15:01 UTC
Time.gm(2000,"jan",1,20,15,1)   #=> 2000-01-01 20:15:01 UTC
代码语言:javascript
复制
static VALUE
time_s_mkutc(int argc, VALUE *argv, VALUE klass)
{
    return time_utc_or_local(argc, argv, TRUE, klass);
}

w3cdtf(date) Show source

此方法将W3CDTF字符串日期/时间格式转换为Time对象。

W3CDTF格式在此定义:www.w3.org/TR/NOTE-datetime

代码语言:javascript
复制
Time.w3cdtf('2003-02-15T13:50:05-05:00')
# => 2003-02-15 10:50:05 -0800
Time.w3cdtf('2003-02-15T13:50:05-05:00').class
# => Time
代码语言:javascript
复制
# File lib/rss/rss.rb, line 14
def w3cdtf(date)
  if /\A\s*
      (-?\d+)-(\d\d)-(\d\d)
      (?:T
      (\d\d):(\d\d)(?::(\d\d))?
      (\.\d+)?
      (Z|[+-]\d\d:\d\d)?)?
      \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8))
    datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i]
    usec = 0
    usec = $7.to_f * 1000000 if $7
    zone = $8
    if zone
      off = zone_offset(zone, datetime[0])
      datetime = apply_offset(*(datetime + [off]))
      datetime << usec
      time = Time.utc(*datetime)
      force_zone!(time, zone, off)
      time
    else
      datetime << usec
      Time.local(*datetime)
    end
  else
    raise ArgumentError.new("invalid date: #{date.inspect}")
  end
end

xmlschema(date) Show source

解析date为XML Schema定义的dateTime并将其转换为Time对象。格式是ISO 8601定义格式的限制版本。

如果date不符合格式,或者Time类不能表示指定的日期,则引发ArgumentError 。

有关此格式的更多信息,请参阅xmlschema。

你必须要求'time'来使用这种方法。

代码语言:javascript
复制
# File lib/time.rb, line 571
def xmlschema(date)
  if /\A\s*
      (-?\d+)-(\d\d)-(\d\d)
      T
      (\d\d):(\d\d):(\d\d)
      (\.\d+)?
      (Z|[+-]\d\d:\d\d)?
      \s*\z/ix =~ date
    year = $1.to_i
    mon = $2.to_i
    day = $3.to_i
    hour = $4.to_i
    min = $5.to_i
    sec = $6.to_i
    usec = 0
    if $7
      usec = Rational($7) * 1000000
    end
    if $8
      zone = $8
      off = zone_offset(zone)
      year, mon, day, hour, min, sec =
        apply_offset(year, mon, day, hour, min, sec, off)
      t = self.utc(year, mon, day, hour, min, sec, usec)
      force_zone!(t, zone, off)
      t
    else
      self.local(year, mon, day, hour, min, sec, usec)
    end
  else
    raise ArgumentError.new("invalid date: #{date.inspect}")
  end
end

另外别名为:iso8601

zone_offset(zone, year=self.now.year) Show source

返回指定时区与UTC不同的秒数。

数字时区,其中包括分钟,如-10:00+1330将工作,像简单的意志仅一小时的时区-10+13

在ZoneOffset中列出的文本时区也受支持。

如果时区与上述任何一项不符,zone_offset则会检查本地时区(包含和不包含潜在夏时制时间更改生效)是否匹配zone。指定值year将改变用于查找本地时区的年份。

如果zone_offset无法确定偏移量,则返回零。

代码语言:javascript
复制
# File lib/time.rb, line 133
def zone_offset(zone, year=self.now.year)
  off = nil
  zone = zone.upcase
  if /\A([+-])(\d\d):?(\d\d)\z/ =~ zone
    off = ($1 == '-' ? -1 : 1) * ($2.to_i * 60 + $3.to_i) * 60
  elsif /\A[+-]\d\d\z/ =~ zone
    off = zone.to_i * 3600
  elsif ZoneOffset.include?(zone)
    off = ZoneOffset[zone] * 3600
  elsif ((t = self.local(year, 1, 1)).zone.upcase == zone rescue false)
    off = t.utc_offset
  elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false)
    off = t.utc_offset
  end
  off
end

私有类别方法

apply_offset(year, mon, day, hour, min, sec, off) Show source

代码语言:javascript
复制
# File lib/time.rb, line 207
def apply_offset(year, mon, day, hour, min, sec, off)
  if off < 0
    off = -off
    off, o = off.divmod(60)
    if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end
    off, o = off.divmod(60)
    if o != 0 then min += o; o, min = min.divmod(60); off += o end
    off, o = off.divmod(24)
    if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end
    if off != 0
      day += off
      days = month_days(year, mon)
      if days and days < day
        mon += 1
        if 12 < mon
          mon = 1
          year += 1
        end
        day = 1
      end
    end
  elsif 0 < off
    off, o = off.divmod(60)
    if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end
    off, o = off.divmod(60)
    if o != 0 then min -= o; o, min = min.divmod(60); off -= o end
    off, o = off.divmod(24)
    if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end
    if off != 0 then
      day -= off
      if day < 1
        mon -= 1
        if mon < 1
          year -= 1
          mon = 12
        end
        day = month_days(year, mon)
      end
    end
  end
  return year, mon, day, hour, min, sec
end

force_zone!(t, zone, offset=nil) Show source

代码语言:javascript
复制
# File lib/time.rb, line 178
def force_zone!(t, zone, offset=nil)
  if zone_utc?(zone)
    t.utc
  elsif offset ||= zone_offset(zone)
    # Prefer the local timezone over the fixed offset timezone because
    # the former is a real timezone and latter is an artificial timezone.
    t.localtime
    if t.utc_offset != offset
      # Use the fixed offset timezone only if the local timezone cannot
      # represent the given offset.
      t.localtime(offset)
    end
  else
    t.localtime
  end
end

make_time(date, year, mon, day, hour, min, sec, sec_fraction, zone, now) Show source

代码语言:javascript
复制
# File lib/time.rb, line 251
def make_time(date, year, mon, day, hour, min, sec, sec_fraction, zone, now)
  if !year && !mon && !day && !hour && !min && !sec && !sec_fraction
    raise ArgumentError, "no time information in #{date.inspect}"
  end

  off = nil
  if year || now
    off_year = year || now.year
    off = zone_offset(zone, off_year) if zone
  end

  if now
    if off
      now = now.getlocal(off) if now.utc_offset != off
    else
      now = now.getlocal
    end
  end

  usec = nil
  usec = sec_fraction * 1000000 if sec_fraction

  if now
    begin
      break if year; year = now.year
      break if mon; mon = now.mon
      break if day; day = now.day
      break if hour; hour = now.hour
      break if min; min = now.min
      break if sec; sec = now.sec
      break if sec_fraction; usec = now.tv_usec
    end until true
  end

  year ||= 1970
  mon ||= 1
  day ||= 1
  hour ||= 0
  min ||= 0
  sec ||= 0
  usec ||= 0

  if year != off_year
    off = nil
    off = zone_offset(zone, year) if zone
  end

  if off
    year, mon, day, hour, min, sec =
      apply_offset(year, mon, day, hour, min, sec, off)
    t = self.utc(year, mon, day, hour, min, sec, usec)
    force_zone!(t, zone, off)
    t
  else
    self.local(year, mon, day, hour, min, sec, usec)
  end
end

month_days(y, m) Show source

代码语言:javascript
复制
# File lib/time.rb, line 198
def month_days(y, m)
  if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
    LeapYearMonthDays[m-1]
  else
    CommonYearMonthDays[m-1]
  end
end

zone_utc?(zone) Show source

代码语言:javascript
复制
# File lib/time.rb, line 150
def zone_utc?(zone)
  # * +0000
  #   In RFC 2822, +0000 indicate a time zone at Universal Time.
  #   Europe/Lisbon is "a time zone at Universal Time" in Winter.
  #   Atlantic/Reykjavik is "a time zone at Universal Time".
  #   Africa/Dakar is "a time zone at Universal Time".
  #   So +0000 is a local time such as Europe/London, etc.
  # * GMT
  #   GMT is used as a time zone abbreviation in Europe/London,
  #   Africa/Dakar, etc.
  #   So it is a local time.
  #
  # * -0000, -00:00
  #   In RFC 2822, -0000 the date-time contains no information about the
  #   local time zone.
  #   In RFC 3339, -00:00 is used for the time in UTC is known,
  #   but the offset to local time is unknown.
  #   They are not appropriate for specific time zone such as
  #   Europe/London because time zone neutral,
  #   So -00:00 and -0000 are treated as UTC.
  if /\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i =~ zone
    true
  else
    false
  end
end

公共实例方法

time + numeric → time Show source

加法 - 向时间添加若干秒(可能为小数),并将该值作为新的时间对象返回。

代码语言:javascript
复制
t = Time.now         #=> 2007-11-19 08:22:21 -0600
t + (60 * 60 * 24)   #=> 2007-11-20 08:22:21 -0600
代码语言:javascript
复制
static VALUE
time_plus(VALUE time1, VALUE time2)
{
    struct time_object *tobj;
    GetTimeval(time1, tobj);

    if (IsTimeval(time2)) {
        rb_raise(rb_eTypeError, "time + time?");
    }
    return time_add(tobj, time2, 1);
}

time - other_time → float Show source

time - numeric → time

差异 - 返回一个新的时间对象,表示时间和之间的差异other_time,或者numeric时间中减去给定的秒数。

代码语言:javascript
复制
t = Time.now       #=> 2007-11-19 08:23:10 -0600
t2 = t + 2592000   #=> 2007-12-19 08:23:10 -0600
t2 - t             #=> 2592000.0
t2 - 2592000       #=> 2007-11-19 08:23:10 -0600
代码语言:javascript
复制
static VALUE
time_minus(VALUE time1, VALUE time2)
{
    struct time_object *tobj;

    GetTimeval(time1, tobj);
    if (IsTimeval(time2)) {
        struct time_object *tobj2;

        GetTimeval(time2, tobj2);
        return rb_Float(rb_time_unmagnify_to_float(wsub(tobj->timew, tobj2->timew)));
    }
    return time_add(tobj, time2, -1);
}

time <=> other_time → -1, 0, +1 or nil Show source

比较 - timeother_time

-1,0,+1或零,取决于time是小于,等于还是大于other_time

如果两个值无法比较,则返回nil

代码语言:javascript
复制
t = Time.now       #=> 2007-11-19 08:12:12 -0600
t2 = t + 2592000   #=> 2007-12-19 08:12:12 -0600
t <=> t2           #=> -1
t2 <=> t           #=> 1

t = Time.now       #=> 2007-11-19 08:13:38 -0600
t2 = t + 0.1       #=> 2007-11-19 08:13:38 -0600
t.nsec             #=> 98222999
t2.nsec            #=> 198222999
t <=> t2           #=> -1
t2 <=> t           #=> 1
t <=> t            #=> 0
代码语言:javascript
复制
static VALUE
time_cmp(VALUE time1, VALUE time2)
{
    struct time_object *tobj1, *tobj2;
    int n;

    GetTimeval(time1, tobj1);
    if (IsTimeval(time2)) {
        GetTimeval(time2, tobj2);
        n = wcmp(tobj1->timew, tobj2->timew);
    }
    else {
        return rb_invcmp(time1, time2);
    }
    if (n == 0) return INT2FIX(0);
    if (n > 0) return INT2FIX(1);
    return INT2FIX(-1);
}

as_json(*) Show source

返回一个散列,它将变成一个JSON对象并表示这个对象。

代码语言:javascript
复制
# File ext/json/lib/json/add/time.rb, line 22
def as_json(*)
  nanoseconds = [ tv_usec * 1000 ]
  respond_to?(:tv_nsec) and nanoseconds << tv_nsec
  nanoseconds = nanoseconds.max
  {
    JSON.create_id => self.class.name,
    's'            => tv_sec,
    'n'            => nanoseconds,
  }
end

asctime → string Show source

返回的规范的字符串表示的时间

代码语言:javascript
复制
Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"
Time.now.ctime     #=> "Wed Apr  9 08:56:03 2003"
代码语言:javascript
复制
static VALUE
time_asctime(VALUE time)
{
    return strftimev("%a %b %e %T %Y", time, rb_usascii_encoding());
}

ctime → string Show source

返回的规范的字符串表示的时间

代码语言:javascript
复制
Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"
Time.now.ctime     #=> "Wed Apr  9 08:56:03 2003"
代码语言:javascript
复制
static VALUE
time_asctime(VALUE time)
{
    return strftimev("%a %b %e %T %Y", time, rb_usascii_encoding());
}

day → integer Show source

返回月份(1..N)的一天时间

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:27:03 -0600
t.day          #=> 19
t.mday         #=> 19
代码语言:javascript
复制
static VALUE
time_mday(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.mday);
}

dst? → true or false Show source

返回true如果时间在其时区夏令时期间发生。

代码语言:javascript
复制
# CST6CDT:
  Time.local(2000, 1, 1).zone    #=> "CST"
  Time.local(2000, 1, 1).isdst   #=> false
  Time.local(2000, 1, 1).dst?    #=> false
  Time.local(2000, 7, 1).zone    #=> "CDT"
  Time.local(2000, 7, 1).isdst   #=> true
  Time.local(2000, 7, 1).dst?    #=> true

# Asia/Tokyo:
  Time.local(2000, 1, 1).zone    #=> "JST"
  Time.local(2000, 1, 1).isdst   #=> false
  Time.local(2000, 1, 1).dst?    #=> false
  Time.local(2000, 7, 1).zone    #=> "JST"
  Time.local(2000, 7, 1).isdst   #=> false
  Time.local(2000, 7, 1).dst?    #=> false
代码语言:javascript
复制
static VALUE
time_isdst(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return tobj->vtm.isdst ? Qtrue : Qfalse;
}

eql?(other_time) Show source

如果是时间并且other_time都是具有相同秒和小数秒的Time对象,则返回true

代码语言:javascript
复制
static VALUE
time_eql(VALUE time1, VALUE time2)
{
    struct time_object *tobj1, *tobj2;

    GetTimeval(time1, tobj1);
    if (IsTimeval(time2)) {
        GetTimeval(time2, tobj2);
        return rb_equal(w2v(tobj1->timew), w2v(tobj2->timew));
    }
    return Qfalse;
}

friday? → true or false Show source

如果时间代表星期五返回true

代码语言:javascript
复制
t = Time.local(1987, 12, 18)     #=> 1987-12-18 00:00:00 -0600
t.friday?                        #=> true
代码语言:javascript
复制
static VALUE
time_friday(VALUE time)
{
    wday_p(5);
}

getgm → new_time Show source

返回表示新的时间对象时间在UTC。

代码语言:javascript
复制
t = Time.local(2000,1,1,20,15,1)   #=> 2000-01-01 20:15:01 -0600
t.gmt?                             #=> false
y = t.getgm                        #=> 2000-01-02 02:15:01 UTC
y.gmt?                             #=> true
t == y                             #=> true
代码语言:javascript
复制
static VALUE
time_getgmtime(VALUE time)
{
    return time_gmtime(time_dup(time));
}

getlocal → new_time Show source

getlocal(utc_offset) → new_time

返回表示新的时间对象时间在本地时间(使用效果本地时区的这一过程)。

如果utc_offset给出,它将被用来代替当地时间.utc_offset可以作为人类可读的字符串(例如."+09:00")或以秒数(例如.32400)的形式给出。

代码语言:javascript
复制
t = Time.utc(2000,1,1,20,15,1)  #=> 2000-01-01 20:15:01 UTC
t.utc?                          #=> true

l = t.getlocal                  #=> 2000-01-01 14:15:01 -0600
l.utc?                          #=> false
t == l                          #=> true

j = t.getlocal("+09:00")        #=> 2000-01-02 05:15:01 +0900
j.utc?                          #=> false
t == j                          #=> true

k = t.getlocal(9*60*60)         #=> 2000-01-02 05:15:01 +0900
k.utc?                          #=> false
t == k                          #=> true
代码语言:javascript
复制
static VALUE
time_getlocaltime(int argc, VALUE *argv, VALUE time)
{
    VALUE off;
    rb_scan_args(argc, argv, "01", &off);

    if (!NIL_P(off)) {
        off = utc_offset_arg(off);
        validate_utc_offset(off);

        time = time_dup(time);
        time_set_utc_offset(time, off);
        return time_fixoff(time);
    }

    return time_localtime(time_dup(time));
}

getutc → new_time Show source

返回表示新的时间对象时间在UTC。

代码语言:javascript
复制
t = Time.local(2000,1,1,20,15,1)   #=> 2000-01-01 20:15:01 -0600
t.gmt?                             #=> false
y = t.getgm                        #=> 2000-01-02 02:15:01 UTC
y.gmt?                             #=> true
t == y                             #=> true
代码语言:javascript
复制
static VALUE
time_getgmtime(VALUE time)
{
    return time_gmtime(time_dup(time));
}

gmt? → true or false Show source

如果时间以UTC(GMT)表示时间,则返回true

代码语言:javascript
复制
t = Time.now                        #=> 2007-11-19 08:15:23 -0600
t.utc?                              #=> false
t = Time.gm(2000,"jan",1,20,15,1)   #=> 2000-01-01 20:15:01 UTC
t.utc?                              #=> true

t = Time.now                        #=> 2007-11-19 08:16:03 -0600
t.gmt?                              #=> false
t = Time.gm(2000,1,1,20,15,1)       #=> 2000-01-01 20:15:01 UTC
t.gmt?                              #=> true
代码语言:javascript
复制
static VALUE
time_utc_p(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (TIME_UTC_P(tobj)) return Qtrue;
    return Qfalse;
}

gmt_offset → integer Show source

返回时间和UTC 时间之间的偏移量,以秒为单位。

代码语言:javascript
复制
t = Time.gm(2000,1,1,20,15,1)   #=> 2000-01-01 20:15:01 UTC
t.gmt_offset                    #=> 0
l = t.getlocal                  #=> 2000-01-01 14:15:01 -0600
l.gmt_offset                    #=> -21600
代码语言:javascript
复制
static VALUE
time_utc_offset(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);

    if (TIME_UTC_P(tobj)) {
        return INT2FIX(0);
    }
    else {
        return tobj->vtm.utc_offset;
    }
}

gmtime → time Show source

时间转换为UTC(GMT),修改接收器。

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:18:31 -0600
t.gmt?         #=> false
t.gmtime       #=> 2007-11-19 14:18:31 UTC
t.gmt?         #=> true

t = Time.now   #=> 2007-11-19 08:18:51 -0600
t.utc?         #=> false
t.utc          #=> 2007-11-19 14:18:51 UTC
t.utc?         #=> true
代码语言:javascript
复制
static VALUE
time_gmtime(VALUE time)
{
    struct time_object *tobj;
    struct vtm vtm;

    GetTimeval(time, tobj);
    if (TIME_UTC_P(tobj)) {
        if (tobj->tm_got)
            return time;
    }
    else {
        time_modify(time);
    }

    if (!gmtimew(tobj->timew, &vtm))
        rb_raise(rb_eArgError, "gmtime error");
    tobj->vtm = vtm;

    tobj->tm_got = 1;
    TIME_SET_UTC(tobj);
    return time;
}

gmtoff → integer Show source

返回时间和UTC 时间之间的偏移量,以秒为单位。

代码语言:javascript
复制
t = Time.gm(2000,1,1,20,15,1)   #=> 2000-01-01 20:15:01 UTC
t.gmt_offset                    #=> 0
l = t.getlocal                  #=> 2000-01-01 14:15:01 -0600
l.gmt_offset                    #=> -21600
代码语言:javascript
复制
static VALUE
time_utc_offset(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);

    if (TIME_UTC_P(tobj)) {
        return INT2FIX(0);
    }
    else {
        return tobj->vtm.utc_offset;
    }
}

hash → integer Show source

返回此Time对象的哈希码。

另请参阅Object#hash。

代码语言:javascript
复制
static VALUE
time_hash(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return rb_hash(w2v(tobj->timew));
}

hour → integer Show source

返回一天中的小时(0..23)时间

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:26:20 -0600
t.hour         #=> 8
代码语言:javascript
复制
static VALUE
time_hour(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.hour);
}

httpdate() Show source

返回一个字符串,表示时间为由RFC 2616定义的HTTP-date的RFC 1123日期:

代码语言:javascript
复制
day-of-week, DD month-name CCYY hh:mm:ss GMT

请注意,结果始终是UTC(GMT)。

你必须要求'time'来使用这种方法。

代码语言:javascript
复制
# File lib/time.rb, line 653
def httpdate
  t = dup.utc
  sprintf('%s, %02d %s %0*d %02d:%02d:%02d GMT',
    RFC2822_DAY_NAME[t.wday],
    t.day, RFC2822_MONTH_NAME[t.mon-1], t.year < 0 ? 5 : 4, t.year,
    t.hour, t.min, t.sec)
end

inspect → string Show source

返回表示时间的字符串。相当于用适当的格式字符串调用strftime。

代码语言:javascript
复制
t = Time.now
t.to_s                              => "2012-11-10 18:16:12 +0100"
t.strftime "%Y-%m-%d %H:%M:%S %z"   => "2012-11-10 18:16:12 +0100"

t.utc.to_s                          => "2012-11-10 17:16:12 UTC"
t.strftime "%Y-%m-%d %H:%M:%S UTC"  => "2012-11-10 17:16:12 UTC"
代码语言:javascript
复制
static VALUE
time_to_s(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (TIME_UTC_P(tobj))
        return strftimev("%Y-%m-%d %H:%M:%S UTC", time, rb_usascii_encoding());
    else
        return strftimev("%Y-%m-%d %H:%M:%S %z", time, rb_usascii_encoding());
}

isdst → true or false Show source

如果时间在其时区夏令时期间发生,返回true

代码语言:javascript
复制
# CST6CDT:
  Time.local(2000, 1, 1).zone    #=> "CST"
  Time.local(2000, 1, 1).isdst   #=> false
  Time.local(2000, 1, 1).dst?    #=> false
  Time.local(2000, 7, 1).zone    #=> "CDT"
  Time.local(2000, 7, 1).isdst   #=> true
  Time.local(2000, 7, 1).dst?    #=> true

# Asia/Tokyo:
  Time.local(2000, 1, 1).zone    #=> "JST"
  Time.local(2000, 1, 1).isdst   #=> false
  Time.local(2000, 1, 1).dst?    #=> false
  Time.local(2000, 7, 1).zone    #=> "JST"
  Time.local(2000, 7, 1).isdst   #=> false
  Time.local(2000, 7, 1).dst?    #=> false
代码语言:javascript
复制
static VALUE
time_isdst(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return tobj->vtm.isdst ? Qtrue : Qfalse;
}

iso8601(fraction_digits=0)

别名为:xmlschema

localtime → time Show source

localtime(utc_offset) → time

时间转换为本地时间(使用本过程的本地时区)修改接收器。

如果utc_offset给出,它将被用来代替当地时间。

代码语言:javascript
复制
t = Time.utc(2000, "jan", 1, 20, 15, 1) #=> 2000-01-01 20:15:01 UTC
t.utc?                                  #=> true

t.localtime                             #=> 2000-01-01 14:15:01 -0600
t.utc?                                  #=> false

t.localtime("+09:00")                   #=> 2000-01-02 05:15:01 +0900
t.utc?                                  #=> false
代码语言:javascript
复制
static VALUE
time_localtime_m(int argc, VALUE *argv, VALUE time)
{
    VALUE off;
    rb_scan_args(argc, argv, "01", &off);

    if (!NIL_P(off)) {
        off = utc_offset_arg(off);
        validate_utc_offset(off);

        time_set_utc_offset(time, off);
        return time_fixoff(time);
    }

    return time_localtime(time);
}

mday → integer Show source

返回月份(1..N)的一天时间

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:27:03 -0600
t.day          #=> 19
t.mday         #=> 19
代码语言:javascript
复制
static VALUE
time_mday(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.mday);
}

min → integer Show source

返回小时(0..59)为的分钟时间

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:25:51 -0600
t.min          #=> 25
代码语言:javascript
复制
static VALUE
time_min(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.min);
}

mon → integer Show source

month → integer

返回年份(1..12)的一个月时间

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:27:30 -0600
t.mon          #=> 11
t.month        #=> 11
代码语言:javascript
复制
static VALUE
time_mon(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.mon);
}

monday? → true or false Show source

如果时间代表星期一返回true

代码语言:javascript
复制
t = Time.local(2003, 8, 4)       #=> 2003-08-04 00:00:00 -0500
p t.monday?                      #=> true
代码语言:javascript
复制
static VALUE
time_monday(VALUE time)
{
    wday_p(1);
}

month → integer Show source

返回年份(1..12)的一个月时间

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:27:30 -0600
t.mon          #=> 11
t.month        #=> 11
代码语言:javascript
复制
static VALUE
time_mon(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.mon);
}

nsec → int Show source

返回时间的纳秒数。

代码语言:javascript
复制
t = Time.now        #=> 2007-11-17 15:18:03 +0900
"%10.9f" % t.to_f   #=> "1195280283.536151409"
t.nsec              #=> 536151406

to_f和nsec的最低位数不同,因为IEEE 754双精度不足以表示从Epoch开始的精确的纳秒数。

更精确的值由nsec返回。

代码语言:javascript
复制
static VALUE
time_nsec(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return rb_to_int(w2v(wmulquoll(wmod(tobj->timew, WINT2WV(TIME_SCALE)), 1000000000, TIME_SCALE)));
}

rfc2822() Show source

返回一个字符串,它将时间表示为由RFC 2822定义的日期时间:

代码语言:javascript
复制
day-of-week, DD month-name CCYY hh:mm:ss zone

其中区域是+ -hhmm。

如果self是UTC时间,则将-0000用作区域。

你必须要求'time'来使用这种方法。

代码语言:javascript
复制
# File lib/time.rb, line 618
def rfc2822
  sprintf('%s, %02d %s %0*d %02d:%02d:%02d ',
    RFC2822_DAY_NAME[wday],
    day, RFC2822_MONTH_NAME[mon-1], year < 0 ? 5 : 4, year,
    hour, min, sec) <<
  if utc?
    '-0000'
  else
    off = utc_offset
    sign = off < 0 ? '-' : '+'
    sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60))
  end
end

另外别名为:rfc822

rfc822()

别名为:rfc2822

round(ndigits) → new_time Show source

以秒为单位将子秒数循环到一个给定的精度(默认为0位)。它返回一个新的Time对象。ndigits应该是零或正整数。

代码语言:javascript
复制
require 'time'

t = Time.utc(2010,3,30, 5,43,"25.123456789".to_r)
p t.iso8601(10)           #=> "2010-03-30T05:43:25.1234567890Z"
p t.round.iso8601(10)     #=> "2010-03-30T05:43:25.0000000000Z"
p t.round(0).iso8601(10)  #=> "2010-03-30T05:43:25.0000000000Z"
p t.round(1).iso8601(10)  #=> "2010-03-30T05:43:25.1000000000Z"
p t.round(2).iso8601(10)  #=> "2010-03-30T05:43:25.1200000000Z"
p t.round(3).iso8601(10)  #=> "2010-03-30T05:43:25.1230000000Z"
p t.round(4).iso8601(10)  #=> "2010-03-30T05:43:25.1235000000Z"
p t.round(5).iso8601(10)  #=> "2010-03-30T05:43:25.1234600000Z"
p t.round(6).iso8601(10)  #=> "2010-03-30T05:43:25.1234570000Z"
p t.round(7).iso8601(10)  #=> "2010-03-30T05:43:25.1234568000Z"
p t.round(8).iso8601(10)  #=> "2010-03-30T05:43:25.1234567900Z"
p t.round(9).iso8601(10)  #=> "2010-03-30T05:43:25.1234567890Z"
p t.round(10).iso8601(10) #=> "2010-03-30T05:43:25.1234567890Z"

t = Time.utc(1999,12,31, 23,59,59)
p((t + 0.4).round.iso8601(3))    #=> "1999-12-31T23:59:59.000Z"
p((t + 0.49).round.iso8601(3))   #=> "1999-12-31T23:59:59.000Z"
p((t + 0.5).round.iso8601(3))    #=> "2000-01-01T00:00:00.000Z"
p((t + 1.4).round.iso8601(3))    #=> "2000-01-01T00:00:00.000Z"
p((t + 1.49).round.iso8601(3))   #=> "2000-01-01T00:00:00.000Z"
p((t + 1.5).round.iso8601(3))    #=> "2000-01-01T00:00:01.000Z"

t = Time.utc(1999,12,31, 23,59,59)
p (t + 0.123456789).round(4).iso8601(6)  #=> "1999-12-31T23:59:59.123500Z"
代码语言:javascript
复制
static VALUE
time_round(int argc, VALUE *argv, VALUE time)
{
    VALUE ndigits, v, a, b, den;
    long nd;
    struct time_object *tobj;

    rb_scan_args(argc, argv, "01", &ndigits);

    if (NIL_P(ndigits))
        ndigits = INT2FIX(0);
    else
        ndigits = rb_to_int(ndigits);

    nd = NUM2LONG(ndigits);
    if (nd < 0)
        rb_raise(rb_eArgError, "negative ndigits given");

    GetTimeval(time, tobj);
    v = w2v(rb_time_unmagnify(tobj->timew));

    a = INT2FIX(1);
    b = INT2FIX(10);
    while (0 < nd) {
        if (nd & 1)
            a = mul(a, b);
        b = mul(b, b);
        nd = nd >> 1;
    }
    den = quo(INT2FIX(1), a);
    v = mod(v, den);
    if (lt(v, quo(den, INT2FIX(2))))
        return time_add(tobj, v, -1);
    else
        return time_add(tobj, sub(den, v), 1);
}

saturday? → true or false Show source

如果时间代表星期六返回true

代码语言:javascript
复制
t = Time.local(2006, 6, 10)      #=> 2006-06-10 00:00:00 -0500
t.saturday?                      #=> true
代码语言:javascript
复制
static VALUE
time_saturday(VALUE time)
{
    wday_p(6);
}

sec → integer Show source

返回分钟(0..60)为第二时间

注意:秒的范围从0到60,以允许系统注入闰秒。有关更多详细信息,请参见en.wikipedia.org/wiki/Leap_second

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:25:02 -0600
t.sec          #=> 2
代码语言:javascript
复制
static VALUE
time_sec(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.sec);
}

strftime( string ) → string Show source

根据给定格式字符串中的指令格式化时间

指令以百分号(%)字符开头。任何未作为指令列出的文本都将传递到输出字符串。

该指令由百分号(%)字符,零个或多个标志,可选的最小字段宽度,可选的修饰符和转换说明符组成,如下所示:

代码语言:javascript
复制
%<flags><width><modifier><conversion>

Flags:

代码语言:javascript
复制
-  don't pad a numerical output
_  use spaces for padding
0  use zeros for padding
^  upcase the result string
#  change case
:  use colons for %z

最小字段宽度指定最小宽度。

修饰符是“E”和“O”。他们被忽略。

格式指南:

代码语言:javascript
复制
Date (Year, Month, Day):
  %Y - Year with century if provided, will pad result at least 4 digits.
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (rounded down such as 20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..60)

  %L - Millisecond of the second (000..999)
       The digits under millisecond are truncated to not produce 1000.
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)
          %15N femtosecond (15 digits)
          %18N attosecond (18 digits)
          %21N zeptosecond (21 digits)
          %24N yoctosecond (24 digits)
       The digits under the specified length are truncated to avoid
       carry up.

Time zone:
  %z - Time zone as hour and minute offset from UTC (e.g. +0900)
          %:z - hour and minute offset from UTC with a colon (e.g. +09:00)
          %::z - hour, minute and second offset from UTC (e.g. +09:00:00)
  %Z - Abbreviated time zone name or similar information.  (OS dependent)

Weekday:
  %A - The full weekday name (``Sunday'')
          %^A  uppercased (``SUNDAY'')
  %a - The abbreviated name (``Sun'')
          %^a  uppercased (``SUN'')
  %u - Day of the week (Monday is 1, 1..7)
  %w - Day of the week (Sunday is 0, 0..6)

ISO 8601 week-based year and week number:
The first week of YYYY starts with a Monday and includes YYYY-01-04.
The days in the year before the first week are in the last week of
the previous year.
  %G - The week-based year
  %g - The last 2 digits of the week-based year (00..99)
  %V - Week number of the week-based year (01..53)

Week number:
The first week of YYYY that starts with a Sunday or Monday (according to %U
or %W). The days in the year before the first week are in week 0.
  %U - Week number of the year. The week starts with Sunday. (00..53)
  %W - Week number of the year. The week starts with Monday. (00..53)

Seconds since the Epoch:
  %s - Number of seconds since 1970-01-01 00:00:00 UTC.

Literal string:
  %n - Newline character (\n)
  %t - Tab character (\t)
  %% - Literal ``%'' character

Combination:
  %c - date and time (%a %b %e %T %Y)
  %D - Date (%m/%d/%y)
  %F - The ISO 8601 date format (%Y-%m-%d)
  %v - VMS date (%e-%^b-%4Y)
  %x - Same as %D
  %X - Same as %T
  %r - 12-hour time (%I:%M:%S %p)
  %R - 24-hour time (%H:%M)
  %T - 24-hour time (%H:%M:%S)

该方法与ISO C和POSIX中定义的strftime()函数类似。

尽管从Ruby 1.9开始,所有的指令都是独立于locale的,但%Z是依赖于平台的。因此,即使在其他系统(如C)中使用相同的格式字符串,结果也可能不同。

建议%Z比%Z更好。%Z不识别时区。例如,美国/芝加哥(-06:00),美国/哈瓦那(-05:00),亚洲/哈尔滨(+08:00),澳大利亚/达尔文(+09:30)和澳大利亚/阿德莱德(+10:30)。另外,%Z高度依赖于操作系统。例如,它可能会在日语Windows上生成非ASCII字符串。即结果可能与“JST”不同。所以建议使用数字时区偏移量%z。

例子:

代码语言:javascript
复制
t = Time.new(2007,11,19,8,37,48,"-06:00") #=> 2007-11-19 08:37:48 -0600
t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 11/19/2007"
t.strftime("at %I:%M%p")            #=> "at 08:37AM"

各种ISO 8601格式:

代码语言:javascript
复制
%Y%m%d           => 20071119                  Calendar date (basic)
%F               => 2007-11-19                Calendar date (extended)
%Y-%m            => 2007-11                   Calendar date, reduced accuracy, specific month
%Y               => 2007                      Calendar date, reduced accuracy, specific year
%C               => 20                        Calendar date, reduced accuracy, specific century
%Y%j             => 2007323                   Ordinal date (basic)
%Y-%j            => 2007-323                  Ordinal date (extended)
%GW%V%u          => 2007W471                  Week date (basic)
%G-W%V-%u        => 2007-W47-1                Week date (extended)
%GW%V            => 2007W47                   Week date, reduced accuracy, specific week (basic)
%G-W%V           => 2007-W47                  Week date, reduced accuracy, specific week (extended)
%H%M%S           => 083748                    Local time (basic)
%T               => 08:37:48                  Local time (extended)
%H%M             => 0837                      Local time, reduced accuracy, specific minute (basic)
%H:%M            => 08:37                     Local time, reduced accuracy, specific minute (extended)
%H               => 08                        Local time, reduced accuracy, specific hour
%H%M%S,%L        => 083748,000                Local time with decimal fraction, comma as decimal sign (basic)
%T,%L            => 08:37:48,000              Local time with decimal fraction, comma as decimal sign (extended)
%H%M%S.%L        => 083748.000                Local time with decimal fraction, full stop as decimal sign (basic)
%T.%L            => 08:37:48.000              Local time with decimal fraction, full stop as decimal sign (extended)
%H%M%S%z         => 083748-0600               Local time and the difference from UTC (basic)
%T%:z            => 08:37:48-06:00            Local time and the difference from UTC (extended)
%Y%m%dT%H%M%S%z  => 20071119T083748-0600      Date and time of day for calendar date (basic)
%FT%T%:z         => 2007-11-19T08:37:48-06:00 Date and time of day for calendar date (extended)
%Y%jT%H%M%S%z    => 2007323T083748-0600       Date and time of day for ordinal date (basic)
%Y-%jT%T%:z      => 2007-323T08:37:48-06:00   Date and time of day for ordinal date (extended)
%GW%V%uT%H%M%S%z => 2007W471T083748-0600      Date and time of day for week date (basic)
%G-W%V-%uT%T%:z  => 2007-W47-1T08:37:48-06:00 Date and time of day for week date (extended)
%Y%m%dT%H%M      => 20071119T0837             Calendar date and local time (basic)
%FT%R            => 2007-11-19T08:37          Calendar date and local time (extended)
%Y%jT%H%MZ       => 2007323T0837Z             Ordinal date and UTC of day (basic)
%Y-%jT%RZ        => 2007-323T08:37Z           Ordinal date and UTC of day (extended)
%GW%V%uT%H%M%z   => 2007W471T0837-0600        Week date and local time and difference from UTC (basic)
%G-W%V-%uT%R%:z  => 2007-W47-1T08:37-06:00    Week date and local time and difference from UTC (extended)
代码语言:javascript
复制
static VALUE
time_strftime(VALUE time, VALUE format)
{
    struct time_object *tobj;
    const char *fmt;
    long len;
    rb_encoding *enc;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    StringValue(format);
    if (!rb_enc_str_asciicompat_p(format)) {
        rb_raise(rb_eArgError, "format should have ASCII compatible encoding");
    }
    format = rb_str_new4(format);
    fmt = RSTRING_PTR(format);
    len = RSTRING_LEN(format);
    enc = rb_enc_get(format);
    if (len == 0) {
        rb_warning("strftime called with empty format string");
        return rb_enc_str_new(0, 0, enc);
    }
    else {
        VALUE str = rb_strftime_alloc(fmt, len, enc, &tobj->vtm, tobj->timew,
                                      TIME_UTC_P(tobj));
        if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format);
        return str;
    }
}

subsec → number Show source

返回时间分数。

返回值可以是一个有理数。

代码语言:javascript
复制
t = Time.now        #=> 2009-03-26 22:33:12 +0900
"%10.9f" % t.to_f   #=> "1238074392.940563917"
t.subsec            #=> (94056401/100000000)

to_f和subsec的最低位数是不同的,因为IEEE 754双精度不足以表示有理数。

subsec返回更准确的值。

代码语言:javascript
复制
static VALUE
time_subsec(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return quo(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE));
}

succ → new_time Show source

返回一个新的Time对象,比时间晚一秒。#succ自1.9.2开始已经过时,因为时间不是离散值。

代码语言:javascript
复制
t = Time.now       #=> 2007-11-19 08:23:57 -0600
t.succ             #=> 2007-11-19 08:23:58 -0600

改为使用 time + 1

代码语言:javascript
复制
t + 1              #=> 2007-11-19 08:23:58 -0600
代码语言:javascript
复制
VALUE
rb_time_succ(VALUE time)
{
    struct time_object *tobj;
    struct time_object *tobj2;

    rb_warn("Time#succ is obsolete; use time + 1");
    GetTimeval(time, tobj);
    time = time_new_timew(rb_cTime, wadd(tobj->timew, WINT2FIXWV(TIME_SCALE)));
    GetTimeval(time, tobj2);
    TIME_COPY_GMT(tobj2, tobj);
    return time;
}

sunday? → true or false Show source

如果时间表示星期日返回true

代码语言:javascript
复制
t = Time.local(1990, 4, 1)       #=> 1990-04-01 00:00:00 -0600
t.sunday?                        #=> true
代码语言:javascript
复制
static VALUE
time_sunday(VALUE time)
{
    wday_p(0);
}

thursday? → true or false Show source

如果时间代表星期四返回true

代码语言:javascript
复制
t = Time.local(1995, 12, 21)     #=> 1995-12-21 00:00:00 -0600
p t.thursday?                    #=> true
代码语言:javascript
复制
static VALUE
time_thursday(VALUE time)
{
    wday_p(4);
}

to_a → array Show source

返回时间值的十元素数组

代码语言:javascript
复制
[sec, min, hour, day, month, year, wday, yday, isdst, zone]

请参阅各个方法来解释每个值的有效范围。这十个元素可以直接传递给::utc或::local来创建一个新的Time对象。

代码语言:javascript
复制
t = Time.now     #=> 2007-11-19 08:36:01 -0600
now = t.to_a     #=> [1, 36, 8, 19, 11, 2007, 1, 323, false, "CST"]
代码语言:javascript
复制
static VALUE
time_to_a(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return rb_ary_new3(10,
                    INT2FIX(tobj->vtm.sec),
                    INT2FIX(tobj->vtm.min),
                    INT2FIX(tobj->vtm.hour),
                    INT2FIX(tobj->vtm.mday),
                    INT2FIX(tobj->vtm.mon),
                    tobj->vtm.year,
                    INT2FIX(tobj->vtm.wday),
                    INT2FIX(tobj->vtm.yday),
                    tobj->vtm.isdst?Qtrue:Qfalse,
                    time_zone(time));
}

to_date → date Show source

返回一个表示self的Date对象。

代码语言:javascript
复制
static VALUE
time_to_date(VALUE self)
{
    VALUE y, nth, ret;
    int ry, m, d;

    y = f_year(self);
    m = FIX2INT(f_mon(self));
    d = FIX2INT(f_mday(self));

    decode_year(y, -1, &nth, &ry);

    ret = d_simple_new_internal(cDate,
                                nth, 0,
                                GREGORIAN,
                                ry, m, d,
                                HAVE_CIVIL);
    {
        get_d1(ret);
        set_sg(dat, DEFAULT_SG);
    }
    return ret;
}

to_datetime → datetime Show source

返回表示自我的DateTime对象。

代码语言:javascript
复制
static VALUE
time_to_datetime(VALUE self)
{
    VALUE y, sf, nth, ret;
    int ry, m, d, h, min, s, of;

    y = f_year(self);
    m = FIX2INT(f_mon(self));
    d = FIX2INT(f_mday(self));

    h = FIX2INT(f_hour(self));
    min = FIX2INT(f_min(self));
    s = FIX2INT(f_sec(self));
    if (s == 60)
        s = 59;

    sf = sec_to_ns(f_subsec(self));
    of = FIX2INT(f_utc_offset(self));

    decode_year(y, -1, &nth, &ry);

    ret = d_complex_new_internal(cDateTime,
                                 nth, 0,
                                 0, sf,
                                 of, DEFAULT_SG,
                                 ry, m, d,
                                 h, min, s,
                                 HAVE_CIVIL | HAVE_TIME);
    {
        get_d1(ret);
        set_sg(dat, DEFAULT_SG);
    }
    return ret;
}

to_f → float Show source

从Epoch开始,以秒为单位返回时间值。

代码语言:javascript
复制
t = Time.now
"%10.5f" % t.to_f   #=> "1270968744.77658"
t.to_i              #=> 1270968744

请注意,IEEE 754双精度不足以表示自Epoch以来的纳秒数。

代码语言:javascript
复制
static VALUE
time_to_f(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return rb_Float(rb_time_unmagnify_to_float(tobj->timew));
}

to_i → int Show source

从Epoch开始,以秒为单位返回时间值。

代码语言:javascript
复制
t = Time.now
"%10.5f" % t.to_f   #=> "1270968656.89607"
t.to_i              #=> 1270968656
代码语言:javascript
复制
static VALUE
time_to_i(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return w2v(wdiv(tobj->timew, WINT2FIXWV(TIME_SCALE)));
}

to_json(*args) Show source

存储类名称(时间),包含自epoch以来的秒数以及时间的微秒数作为JSON字符串

代码语言:javascript
复制
# File ext/json/lib/json/add/time.rb, line 35
def to_json(*args)
  as_json.to_json(*args)
end

to_r → a_rational Show source

从Epoch开始,以秒为单位返回时间值。

代码语言:javascript
复制
t = Time.now
p t.to_r            #=> (1270968792716287611/1000000000)

此方法旨在用于获取表示自Epoch以来纳秒级的准确值。您可以使用此方法将时间转换为另一个Epoch。

代码语言:javascript
复制
static VALUE
time_to_r(VALUE time)
{
    struct time_object *tobj;
    VALUE v;

    GetTimeval(time, tobj);
    v = w2v(rb_time_unmagnify(tobj->timew));
    if (!RB_TYPE_P(v, T_RATIONAL)) {
        v = rb_Rational1(v);
    }
    return v;
}

to_s → string Show source

返回表示时间的字符串。相当于用适当的格式字符串调用strftime。

代码语言:javascript
复制
t = Time.now
t.to_s                              => "2012-11-10 18:16:12 +0100"
t.strftime "%Y-%m-%d %H:%M:%S %z"   => "2012-11-10 18:16:12 +0100"

t.utc.to_s                          => "2012-11-10 17:16:12 UTC"
t.strftime "%Y-%m-%d %H:%M:%S UTC"  => "2012-11-10 17:16:12 UTC"
代码语言:javascript
复制
static VALUE
time_to_s(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (TIME_UTC_P(tobj))
        return strftimev("%Y-%m-%d %H:%M:%S UTC", time, rb_usascii_encoding());
    else
        return strftimev("%Y-%m-%d %H:%M:%S %z", time, rb_usascii_encoding());
}

to_time → time Show source

返回self。

代码语言:javascript
复制
static VALUE
time_to_time(VALUE self)
{
    return self;
}

tuesday? → true or false Show source

如果时间代表星期二返回true

代码语言:javascript
复制
t = Time.local(1991, 2, 19)      #=> 1991-02-19 00:00:00 -0600
p t.tuesday?                     #=> true
代码语言:javascript
复制
static VALUE
time_tuesday(VALUE time)
{
    wday_p(2);
}

tv_nsec → int Show source

返回时间的纳秒数。

代码语言:javascript
复制
t = Time.now        #=> 2007-11-17 15:18:03 +0900
"%10.9f" % t.to_f   #=> "1195280283.536151409"
t.nsec              #=> 536151406

to_f和nsec的最低位数不同,因为IEEE 754双精度不足以表示从Epoch开始的精确的纳秒数。

更精确的值由nsec返回。

代码语言:javascript
复制
static VALUE
time_nsec(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return rb_to_int(w2v(wmulquoll(wmod(tobj->timew, WINT2WV(TIME_SCALE)), 1000000000, TIME_SCALE)));
}

tv_sec → int Show source

从Epoch开始,以秒为单位返回时间值。

代码语言:javascript
复制
t = Time.now
"%10.5f" % t.to_f   #=> "1270968656.89607"
t.to_i              #=> 1270968656
代码语言:javascript
复制
static VALUE
time_to_i(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    return w2v(wdiv(tobj->timew, WINT2FIXWV(TIME_SCALE)));
}

tv_usec → int Show source

返回时间的微秒数。

代码语言:javascript
复制
t = Time.now        #=> 2007-11-19 08:03:26 -0600
"%10.6f" % t.to_f   #=> "1195481006.775195"
t.usec              #=> 775195
代码语言:javascript
复制
static VALUE
time_usec(VALUE time)
{
    struct time_object *tobj;
    wideval_t w, q, r;

    GetTimeval(time, tobj);

    w = wmod(tobj->timew, WINT2WV(TIME_SCALE));
    wmuldivmod(w, WINT2FIXWV(1000000), WINT2FIXWV(TIME_SCALE), &q, &r);
    return rb_to_int(w2v(q));
}

usec → int Show source

返回时间的微秒数。

代码语言:javascript
复制
t = Time.now        #=> 2007-11-19 08:03:26 -0600
"%10.6f" % t.to_f   #=> "1195481006.775195"
t.usec              #=> 775195
代码语言:javascript
复制
static VALUE
time_usec(VALUE time)
{
    struct time_object *tobj;
    wideval_t w, q, r;

    GetTimeval(time, tobj);

    w = wmod(tobj->timew, WINT2WV(TIME_SCALE));
    wmuldivmod(w, WINT2FIXWV(1000000), WINT2FIXWV(TIME_SCALE), &q, &r);
    return rb_to_int(w2v(q));
}

gmtime → time Show source

utc → time

时间转换为UTC(GMT),修改接收器。

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:18:31 -0600
t.gmt?         #=> false
t.gmtime       #=> 2007-11-19 14:18:31 UTC
t.gmt?         #=> true

t = Time.now   #=> 2007-11-19 08:18:51 -0600
t.utc?         #=> false
t.utc          #=> 2007-11-19 14:18:51 UTC
t.utc?         #=> true
代码语言:javascript
复制
static VALUE
time_gmtime(VALUE time)
{
    struct time_object *tobj;
    struct vtm vtm;

    GetTimeval(time, tobj);
    if (TIME_UTC_P(tobj)) {
        if (tobj->tm_got)
            return time;
    }
    else {
        time_modify(time);
    }

    if (!gmtimew(tobj->timew, &vtm))
        rb_raise(rb_eArgError, "gmtime error");
    tobj->vtm = vtm;

    tobj->tm_got = 1;
    TIME_SET_UTC(tobj);
    return time;
}

utc? → true or false Show source

如果时间以UTC(GMT)表示时间,则返回true

代码语言:javascript
复制
t = Time.now                        #=> 2007-11-19 08:15:23 -0600
t.utc?                              #=> false
t = Time.gm(2000,"jan",1,20,15,1)   #=> 2000-01-01 20:15:01 UTC
t.utc?                              #=> true

t = Time.now                        #=> 2007-11-19 08:16:03 -0600
t.gmt?                              #=> false
t = Time.gm(2000,1,1,20,15,1)       #=> 2000-01-01 20:15:01 UTC
t.gmt?                              #=> true
代码语言:javascript
复制
static VALUE
time_utc_p(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (TIME_UTC_P(tobj)) return Qtrue;
    return Qfalse;
}

utc_offset → integer Show source

返回时间和UTC 时间之间的偏移量,以秒为单位。

代码语言:javascript
复制
t = Time.gm(2000,1,1,20,15,1)   #=> 2000-01-01 20:15:01 UTC
t.gmt_offset                    #=> 0
l = t.getlocal                  #=> 2000-01-01 14:15:01 -0600
l.gmt_offset                    #=> -21600
代码语言:javascript
复制
static VALUE
time_utc_offset(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);

    if (TIME_UTC_P(tobj)) {
        return INT2FIX(0);
    }
    else {
        return tobj->vtm.utc_offset;
    }
}

w3cdtf() Show source

此方法将Time对象转换为String。该字符串包含W3CDTF date/time格式的时间。

W3CDTF格式在此定义:www.w3.org/TR/NOTE-datetime

代码语言:javascript
复制
Time.now.w3cdtf
# => "2013-08-26T14:12:10.817124-07:00"
代码语言:javascript
复制
# File lib/rss/rss.rb, line 52
def w3cdtf
  if usec.zero?
    fraction_digits = 0
  else
    fraction_digits = strftime('%6N').index(/0*\z/)
  end
  xmlschema(fraction_digits)
end

wday → integer Show source

返回一个整数,表示星期几,0..6,星期天== 0。

代码语言:javascript
复制
t = Time.now   #=> 2007-11-20 02:35:35 -0600
t.wday         #=> 2
t.sunday?      #=> false
t.monday?      #=> false
t.tuesday?     #=> true
t.wednesday?   #=> false
t.thursday?    #=> false
t.friday?      #=> false
t.saturday?    #=> false
代码语言:javascript
复制
static VALUE
time_wday(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX((int)tobj->vtm.wday);
}

wednesday? → true or false Show source

如果时间代表星期三返回true

代码语言:javascript
复制
t = Time.local(1993, 2, 24)      #=> 1993-02-24 00:00:00 -0600
p t.wednesday?                   #=> true
代码语言:javascript
复制
static VALUE
time_wednesday(VALUE time)
{
    wday_p(3);
}

xmlschema(fraction_digits=0) Show source

返回一个字符串,它将时间表示为由XML Schema定义的dateTime:

代码语言:javascript
复制
CCYY-MM-DDThh:mm:ssTZD
CCYY-MM-DDThh:mm:ss.sssTZD

TZD是Z或+ -hh:mm。

如果self是UTC时间,则Z用作TZD。否则使用+ -hh:mm。

fractional_digits指定用于小数秒的多个数字。它的默认值是0。

你必须要求'time'来使用这种方法。

代码语言:javascript
复制
# File lib/time.rb, line 677
def xmlschema(fraction_digits=0)
  fraction_digits = fraction_digits.to_i
  s = strftime("%FT%T")
  if fraction_digits > 0
    s << strftime(".%#{fraction_digits}N")
  end
  s << (utc? ? 'Z' : strftime("%:z"))
end

另外别名为:iso8601

yday → integer Show source

返回一个表示一年中的一天的整数,1..366。

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:32:31 -0600
t.yday         #=> 323
代码语言:javascript
复制
static VALUE
time_yday(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.yday);
}

year → integer Show source

返回时间的年份(包括世纪)。

代码语言:javascript
复制
t = Time.now   #=> 2007-11-19 08:27:51 -0600
t.year         #=> 2007
代码语言:javascript
复制
static VALUE
time_year(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return tobj->vtm.year;
}

zone → string Show source

返回用于时间的时区的名称。从Ruby 1.8开始,UTC时间返回“UTC”而不是“GMT”。

代码语言:javascript
复制
t = Time.gm(2000, "jan", 1, 20, 15, 1)
t.zone   #=> "UTC"
t = Time.local(2000, "jan", 1, 20, 15, 1)
t.zone   #=> "CST"
代码语言:javascript
复制
static VALUE
time_zone(VALUE time)
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);

    if (TIME_UTC_P(tobj)) {
        return rb_usascii_str_new_cstr("UTC");
    }
    if (tobj->vtm.zone == NULL)
        return Qnil;

    return time_zone_name(tobj->vtm.zone);
}

扫码关注腾讯云开发者

领取腾讯云代金券