class Time
Time 对象表示一个日期和时间
Time.new(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 -0600
尽管它的值可以表示为单个数值(见下面的 时间戳秒数),但按部分处理该值可能更方便
t = Time.new(-2000, 1, 1, 0, 0, 0.0) # => -2000-01-01 00:00:00 -0600 t.year # => -2000 t.month # => 1 t.mday # => 1 t.hour # => 0 t.min # => 0 t.sec # => 0 t.subsec # => 0 t = Time.new(2000, 12, 31, 23, 59, 59.5) # => 2000-12-31 23:59:59.5 -0600 t.year # => 2000 t.month # => 12 t.mday # => 31 t.hour # => 23 t.min # => 59 t.sec # => 59 t.subsec # => (1/2)
时间戳秒数¶ ↑
时间戳秒数是自 Unix 纪元(1970 年 1 月 1 日)以来的确切秒数(包括小数子秒)。
您可以使用方法 Time.to_r 精确地检索该值
Time.at(0).to_r # => (0/1) Time.at(0.999999).to_r # => (9007190247541737/9007199254740992)
其他检索方法,例如 Time#to_i 和 Time#to_f 可能会返回一个舍入或截断子秒的值。
时间分辨率¶ ↑
从系统时钟派生的 Time 对象(例如,通过方法 Time.now)具有系统支持的分辨率。
时间内部表示¶ ↑
Time 实现使用带符号的 63 位整数、Integer 或 Rational。它是自纪元以来的纳秒数。带符号的 63 位整数可以表示 1823-11-12 到 2116-02-20。当使用 Integer 或 Rational 时(在 1823 年之前、2116 年之后、纳秒以下),Time 的工作速度比使用带符号的 63 位整数时慢。
Ruby 使用 C 函数 localtime 和 gmtime 在数字和 6 元组(年、月、日、小时、分钟、秒)之间进行映射。localtime 用于本地时间,而“gmtime”用于 UTC。
Integer 和 Rational 没有范围限制,但由于 C 类型 time_t 和 struct tm,localtime 和 gmtime 有范围限制。如果超出该限制,Ruby 将外推 localtime 函数。
Time 类始终使用公历。也就是说,使用前摄公历。不支持其他日历,例如儒略历。
如果 time_t 是 32 位带符号整数,则它可以表示 1901-12-14 到 2038-01-19;如果它是 64 位带符号整数,则可以表示 -292277022657-01-27 到 292277026596-12-05。但是,某些平台上的 localtime 不支持负 time_t(1970 年之前)。
struct tm 有一个 tm_year 成员来表示年份。(tm_year = 0 表示 1900 年。)它在 C 标准中定义为 int。如果 int 是 32 位,则 tm_year 可以表示 -2147481748 到 2147485547 之间的值。
如果 C 函数 localtime 和 gmtime 支持,Ruby 就支持闰秒。它们在大多数 Unix 系统中使用 tz 数据库。tz 数据库有支持闰秒的时区。例如,“Asia/Tokyo”不支持闰秒,但“right/Asia/Tokyo”支持闰秒。因此,如果大多数 Unix 系统中的 TZ 环境变量设置为“right/Asia/Tokyo”,Ruby 将支持闰秒。
示例¶ ↑
所有这些示例都使用 EST 时区(GMT-5)完成。
创建新的 Time 实例¶ ↑
您可以使用 Time.new 创建 Time 的新实例。这将使用当前的系统时间。Time.now 是它的别名。您还可以将时间部分(例如年、月、分等)传递给 Time.new。当您想以这种方式构造时间时,您必须至少传递年份。如果您仅传递年份,则时间将默认为该年的 1 月 1 日 00:00:00,并且使用当前的系统时区。以下是一些示例
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
您可以传递 UTC 偏移量
Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200
或者 时区对象
zone = timezone("Europe/Athens") # Eastern European Time, UTC+2 Time.new(2002, 10, 31, 2, 2, 2, zone) #=> 2002-10-31 02:02:02 +0200
您还可以使用 Time.local 和 Time.utc 来推断本地时区和 UTC 时区,而不是使用当前的系统设置。
您还可以使用 Time.at 创建新时间,该方法使用自 Unix 纪元以来的秒数(带子秒)。
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500
使用 Time 的实例¶ ↑
一旦您拥有 Time 的实例,您就可以使用它做很多事情。以下是一些示例。对于以下所有示例,我们将假设您已执行以下操作
t = Time.new(1993, 02, 24, 12, 0, 0, "+09:00")
那是星期一吗?
t.monday? #=> false
那是哪一年来着?
t.year #=> 1993
当时是夏令时吗?
t.dst? #=> false
一年后的那天是哪天?
t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900
自 Unix 纪元以来过了多少秒?
t.to_i #=> 730522800
您还可以执行标准函数,例如比较两个时间。
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
这里有什么¶ ↑
首先,看看其他地方有什么。类 Time
- 
继承自 Object 类。 
- 
包含 Comparable 模块。 
在这里,类 Time 提供了对以下操作有用的方法
用于创建的方法¶ ↑
- 
::new:从指定的参数(年、月等)返回一个新的时间,包括可选的时区值。
- 
::at:返回基于自纪元以来的秒数的新时间。
- 
::now:返回基于当前系统时间的新时间。
- 
+(加号):返回增加给定秒数的新时间。
- 
-(减号):返回减少给定秒数的新时间。
用于获取的方法¶ ↑
- 
year:返回时间的年份。
- 
hour:返回时间的小时值。
- 
min:返回时间的分钟值。
- 
sec:返回时间的秒数值。
- 
subsec:返回时间的子秒值。
- 
wday:返回时间的整数工作日值(0 == 星期日)。
- 
yday:返回时间的整数年中日期值(1 == 1 月 1 日)。
- 
hash:返回时间的整数哈希值。
- 
utc_offset(别名为gmt_offset和gmtoff):返回时间与 UTC 之间的秒偏移量。
- 
to_f:返回时间自纪元以来的浮点秒数。
- 
zone:返回时间时区的字符串表示形式。
用于查询的方法¶ ↑
- 
sunday?:返回时间是否为星期日。
- 
monday?:返回时间是否为星期一。
- 
tuesday?:返回时间是否为星期二。
- 
wednesday?:返回时间是否为星期三。
- 
thursday?:返回时间是否为星期四。
- 
friday?:返回时间是否为星期五。
- 
saturday?:返回时间是否为星期六。
用于比较的方法¶ ↑
用于转换的方法¶ ↑
- 
inspect:以详细字符串形式返回时间。
- 
strftime:根据给定的格式,以字符串形式返回时间。
- 
to_a:返回一个包含时间值的 10 元素数组。
- 
to_s:返回时间的字符串表示形式。
- 
getlocal:返回转换为本地时间的新时间。
- 
localtime:将时间转换为本地时间,就地修改。
- 
deconstruct_keys:返回一个用于模式匹配的时间组件哈希。
用于舍入的方法¶ ↑
有关参数 zone 的形式,请参阅 时区指定符。
时区指定符¶ ↑
某些 Time 方法接受指定时区的参数
- 
Time.at:关键字参数in:。
- 
Time.new:位置参数zone或关键字参数in:。
- 
Time.now:关键字参数in:。
- 
Time#getlocal:位置参数zone。
- 
Time#localtime:位置参数zone。
这些方法中的任何一个给定的值都必须是以下值之一(以下详细说明)
时/分偏移量¶ ↑
zone 值可以是 UTC 的字符串偏移量,格式为 '+HH:MM' 或 '-HH:MM',其中
- 
HH是 2 位小时数,范围为0..23。
- 
MM是 2 位分钟数,范围为0..59。
示例
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: '-23:59') # => 1999-12-31 20:16:01 -2359 Time.at(t, in: '+23:59') # => 2000-01-02 20:14:01 +2359
单字母偏移量¶ ↑
zone 值可以是 'A'..'I' 或 'K'..'Z' 范围内的字母;请参阅 军事时区列表
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: 'A') # => 2000-01-01 21:15:01 +0100 Time.at(t, in: 'I') # => 2000-01-02 05:15:01 +0900 Time.at(t, in: 'K') # => 2000-01-02 06:15:01 +1000 Time.at(t, in: 'Y') # => 2000-01-01 08:15:01 -1200 Time.at(t, in: 'Z') # => 2000-01-01 20:15:01 UTC
整数偏移量¶ ↑
zone 值可以是 -86399..86399 范围内的整数秒数
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: -86399) # => 1999-12-31 20:15:02 -235959 Time.at(t, in: 86399) # => 2000-01-02 20:15:00 +235959
时区对象¶ ↑
zone 值可以是一个响应某些时区方法的对象,例如 Timezone 和 TZInfo 的实例。
时区方法是
- 
local_to_utc:当使用 tz作为位置参数zone或关键字参数in:的值调用Time.new时调用。
- 
utc_to_local:当使用 tz作为关键字参数in:的值调用Time.at或Time.now时,以及当使用tz作为位置参数zone的值调用Time#getlocal或Time#localtime时调用。UTC 偏移量将计算为原始时间和返回对象之间的差值,作为 Integer。如果对象位于固定偏移量中,则还会计算其utc_offset。
自定义时区类可以具有这些实例方法,如果定义了这些方法,则将调用这些方法
- 
abbr:当使用涉及 %Z的格式调用Time#strftime时调用。- 参数
- 
一个 类时间对象。 
- 返回
- 
时区名称的字符串缩写。 
 
- 
dst?:当使用 tz作为关键字参数in:的值调用Time.at或Time.now时,以及当使用tz作为位置参数zone的值调用Time#getlocal或Time#localtime时调用。- 参数
- 
一个 类时间对象。 
- 返回
- 
时间是否为夏令时。 
 
- 
name:当调用 Marshal.dump(t)时调用- 参数
- 
无。 
- 返回
- 
时区的字符串名称。 
 
Time-类对象¶ ↑
Time-类对象是一个容器对象,能够与时区库进行时区转换。
上述时区转换方法的参数将具有与 Time 类似的属性,但与时区相关的属性除外,它们是无意义的。
时区对象的 local_to_utc 和 utc_to_local 方法返回的对象可以与其参数的类相同,也可以是任意对象类或 Integer 类。
对于返回的 Integer 以外的类,该类必须具有以下方法
- 
year
- 
mon
- 
mday
- 
hour
- 
min
- 
sec
- 
isdst
对于返回的 Integer,其在 UTC 中分解的组件被解释为指定时区的时间。
时区名称¶ ↑
如果类(类方法的接收者,或实例方法的接收者的类)具有 find_timezone 单例方法,则调用此方法以从时区名称中获取相应的时区对象。
例如,使用 Timezone
class TimeWithTimezone < Time require 'timezone' def self.find_timezone(z) = Timezone[z] end TimeWithTimezone.now(in: "America/New_York") #=> 2023-12-25 00:00:00 -0500 TimeWithTimezone.new("2023-12-25 America/New_York") #=> 2023-12-25 00:00:00 -0500
或者,使用 TZInfo
class TimeWithTZInfo < Time require 'tzinfo' def self.find_timezone(z) = TZInfo::Timezone.get(z) end TimeWithTZInfo.now(in: "America/New_York") #=> 2023-12-25 00:00:00 -0500 TimeWithTZInfo.new("2023-12-25 America/New_York") #=> 2023-12-25 00:00:00 -0500
您可以为每个子类或顶级 Time 类定义此方法。
公共类方法
来源
# File timev.rb, line 323 def self.at(time, subsec = false, unit = :microsecond, in: nil) if Primitive.mandatory_only? Primitive.time_s_at1(time) else Primitive.time_s_at(time, subsec, unit, Primitive.arg!(:in)) end end
根据给定的参数返回一个新的 Time 对象。
必需参数 time 可以是以下任一值
示例
t = Time.new(2000, 12, 31, 23, 59, 59) # => 2000-12-31 23:59:59 -0600 secs = t.to_i # => 978328799 Time.at(secs) # => 2000-12-31 23:59:59 -0600 Time.at(secs + 0.5) # => 2000-12-31 23:59:59.5 -0600 Time.at(1000000000) # => 2001-09-08 20:46:40 -0500 Time.at(0) # => 1969-12-31 18:00:00 -0600 Time.at(-1000000000) # => 1938-04-24 17:13:20 -0500
可选数值参数 subsec 和可选符号参数 units 一起指定返回时间的亚秒数;参数 units 指定 subsec 的单位
- 
:millisecond:subsec以毫秒为单位Time.at(secs, 0, :millisecond) # => 2000-12-31 23:59:59 -0600 Time.at(secs, 500, :millisecond) # => 2000-12-31 23:59:59.5 -0600 Time.at(secs, 1000, :millisecond) # => 2001-01-01 00:00:00 -0600 Time.at(secs, -1000, :millisecond) # => 2000-12-31 23:59:58 -0600 
- 
:microsecond或:usec:subsec以微秒为单位Time.at(secs, 0, :microsecond) # => 2000-12-31 23:59:59 -0600 Time.at(secs, 500000, :microsecond) # => 2000-12-31 23:59:59.5 -0600 Time.at(secs, 1000000, :microsecond) # => 2001-01-01 00:00:00 -0600 Time.at(secs, -1000000, :microsecond) # => 2000-12-31 23:59:58 -0600 
- 
:nanosecond或:nsec:subsec以纳秒为单位Time.at(secs, 0, :nanosecond) # => 2000-12-31 23:59:59 -0600 Time.at(secs, 500000000, :nanosecond) # => 2000-12-31 23:59:59.5 -0600 Time.at(secs, 1000000000, :nanosecond) # => 2001-01-01 00:00:00 -0600 Time.at(secs, -1000000000, :nanosecond) # => 2000-12-31 23:59:58 -0600 
可选关键字参数 in: zone 指定返回时间的时区
Time.at(secs, in: '+12:00') # => 2001-01-01 17:59:59 +1200 Time.at(secs, in: '-12:00') # => 2000-12-31 17:59:59 -1200
有关参数 zone 的形式,请参阅 时区指定符。
来源
# File lib/time.rb, line 569 def httpdate(date) if date.match?(/\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) 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
将 date 解析为 RFC 2616 定义的 HTTP-date,并将其转换为 Time 对象。
如果 date 不符合 RFC 2616 或 Time 类无法表示指定日期,则会引发 ArgumentError。
有关此格式的更多信息,请参阅 httpdate。
require 'time' Time.httpdate("Thu, 06 Oct 2011 02:26:12 GMT") #=> 2011-10-06 02:26:12 UTC
您必须 require 'time' 才能使用此方法。
来源
# 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 at(object['s'], Rational(object['n'], 1000)) end
请参阅 as_json。
来源
static VALUE
time_s_mktime(int argc, VALUE *argv, VALUE klass)
{
    struct vtm vtm;
    time_arg(argc, argv, &vtm);
    return time_localtime(time_new_timew(klass, timelocalw(&vtm)));
}
          类似于 Time.utc,不同之处在于返回的 Time 对象具有本地时区,而不是 UTC 时区
# With seven arguments. Time.local(0, 1, 2, 3, 4, 5, 6) # => 0000-01-02 03:04:05.000006 -0600 # With exactly ten arguments. Time.local(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # => 0005-04-03 02:01:00 -0600
来源
# File timev.rb, line 434 def initialize(year = (now = true), mon = (str = year; nil), mday = nil, hour = nil, min = nil, sec = nil, zone = nil, in: nil, precision: 9) if zone if Primitive.arg!(:in) raise ArgumentError, "timezone argument given as positional and keyword arguments" end else zone = Primitive.arg!(:in) end if now return Primitive.time_init_now(zone) end if str and Primitive.time_init_parse(str, zone, precision) return self end Primitive.time_init_args(year, mon, mday, hour, min, sec, zone) end
根据给定的参数返回一个新的 Time 对象,默认情况下为本地时区。
如果没有位置参数,则返回 Time.now 的值
Time.new # => 2021-04-24 17:27:46.0512465 -0500
如果有一个表示时间的字符串参数,则返回一个新的 Time 对象,该对象基于给定的参数,位于本地时区。
Time.new('2000-12-31 23:59:59.5') # => 2000-12-31 23:59:59.5 -0600 Time.new('2000-12-31 23:59:59.5 +0900') # => 2000-12-31 23:59:59.5 +0900 Time.new('2000-12-31 23:59:59.5', in: '+0900') # => 2000-12-31 23:59:59.5 +0900 Time.new('2000-12-31 23:59:59.5') # => 2000-12-31 23:59:59.5 -0600 Time.new('2000-12-31 23:59:59.56789', precision: 3) # => 2000-12-31 23:59:59.567 -0600
如果有 1 到 6 个参数,则返回一个新的 Time 对象,该对象基于给定的参数,位于本地时区。
Time.new(2000, 1, 2, 3, 4, 5) # => 2000-01-02 03:04:05 -0600
对于位置参数(zone 除外)
- 
year:年份,无范围限制Time.new(999999999) # => 999999999-01-01 00:00:00 -0600 Time.new(-999999999) # => -999999999-01-01 00:00:00 -0600 
- 
month:月份,范围为 (1..12),或不区分大小写的 3 字母月份名称Time.new(2000, 1) # => 2000-01-01 00:00:00 -0600 Time.new(2000, 12) # => 2000-12-01 00:00:00 -0600 Time.new(2000, 'jan') # => 2000-01-01 00:00:00 -0600 Time.new(2000, 'JAN') # => 2000-01-01 00:00:00 -0600 
- 
mday:月份中的天数,范围为 (1..31)Time.new(2000, 1, 1) # => 2000-01-01 00:00:00 -0600 Time.new(2000, 1, 31) # => 2000-01-31 00:00:00 -0600 
- 
hour:小时,范围为 (0..23),如果min、sec和usec为零,则为 24Time.new(2000, 1, 1, 0) # => 2000-01-01 00:00:00 -0600 Time.new(2000, 1, 1, 23) # => 2000-01-01 23:00:00 -0600 Time.new(2000, 1, 1, 24) # => 2000-01-02 00:00:00 -0600 
- 
min:分钟,范围为 (0..59)Time.new(2000, 1, 1, 0, 0) # => 2000-01-01 00:00:00 -0600 Time.new(2000, 1, 1, 0, 59) # => 2000-01-01 00:59:00 -0600 
- 
sec:秒,范围为 (0…61)Time.new(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 -0600 Time.new(2000, 1, 1, 0, 0, 59) # => 2000-01-01 00:00:59 -0600 Time.new(2000, 1, 1, 0, 0, 60) # => 2000-01-01 00:01:00 -0600 Time.new(2000, 1, 1, 0, 0, 59.5) # => 2000-12-31 23:59:59.5 +0900 Time.new(2000, 1, 1, 0, 0, 59.7r) # => 2000-12-31 23:59:59.7 +0900 
这些值可以是
- 
如上所述的整数。 
- 
可转换为整数的数字 Time.new(Float(0.0), Rational(1, 1), 1.0, 0.0, 0.0, 0.0) # => 0000-01-01 00:00:00 -0600 
- 
String整数a = %w[0 1 1 0 0 0] # => ["0", "1", "1", "0", "0", "0"] Time.new(*a) # => 0000-01-01 00:00:00 -0600 
当给定位置参数 zone 或关键字参数 in: 时,新的 Time 对象位于指定的时区中。有关参数 zone 的形式,请参阅 时区指定符
Time.new(2000, 1, 1, 0, 0, 0, '+12:00') # => 2000-01-01 00:00:00 +1200 Time.new(2000, 1, 1, 0, 0, 0, in: '-12:00') # => 2000-01-01 00:00:00 -1200 Time.new(in: '-12:00') # => 2022-08-23 08:49:26.1941467 -1200
由于 in: 关键字参数仅提供默认值,因此如果单字符串形式的第一个参数包含时区信息,则此关键字参数将被静默忽略。
Time.new('2000-01-01 00:00:00 +0100', in: '-0500').utc_offset # => 3600
- 
precision:子秒部分的最大有效位数,默认为 9。超出位数将被截断,与Time的其他操作一样。仅当第一个参数是字符串时才会被使用。
来源
来源
# File lib/time.rb, line 382 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[:yday], d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now) end
接收 Time 的字符串表示形式,并尝试使用启发式方法解析它。
此方法**不**作为验证器工作。如果输入字符串与有效格式不完全匹配,您可能会得到难以理解的结果。应尽可能考虑使用 Time.strptime 而不是此方法。
require 'time' Time.parse("2010-10-31") #=> 2010-10-31 00:00:00 -0500
日期中任何缺失的部分都将根据当前日期推断。
require 'time' # 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)来更改用于推断缺失元素的日期。我们也可以使用我们自己的对象。
require 'time' 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
如果给出了代码块,则 date 中描述的年份将由该代码块转换。这是专门为处理两位数年份而设计的。例如,如果您想将所有 70 之前的两位数年份视为 2000+ 年,您可以这样写:
require 'time' 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
如果给定时间的高位部分损坏或缺失,则会使用 now 的高位部分来补充。对于低位部分,如果损坏或缺失,则假设为最小值(1 或 0)。例如:
require 'time' # 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” 被用作:
-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).zone 和 Time.local(year, 7, 1).zone。如果提取的时区缩写与它们都不匹配,则会被忽略,并且给定的时间将被视为本地时间。
如果 Date._parse 无法从 date 中提取信息,或者 Time 类无法表示指定的日期,则会引发 ArgumentError。
此方法可用作其他解析方法的故障保护措施,例如:
Time.rfc2822(date) rescue Time.parse(date) Time.httpdate(date) rescue Time.parse(date) Time.xmlschema(date) rescue Time.parse(date)
应该检查 Time.parse 的失败情况。
您必须 require 'time' 才能使用此方法。
来源
# File lib/time.rb, line 511 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\d))?\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
将 date 解析为 RFC 2822 定义的日期时间,并将其转换为 Time 对象。该格式与 RFC 822 定义并由 RFC 1123 更新的日期格式相同。
如果 date 不符合 RFC 2822 或 Time 类无法表示指定的日期,则会引发 ArgumentError。
有关此格式的更多信息,请参见 rfc2822。
require 'time' Time.rfc2822("Wed, 05 Oct 2011 22:26:12 -0400") #=> 2010-10-05 22:26:12 -0400
您必须 require 'time' 才能使用此方法。
来源
# File lib/time.rb, line 459 def strptime(date, format, now=self.now) d = Date._strptime(date, format) raise ArgumentError, "invalid date or strptime format - '#{date}' '#{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? yday = d[:yday] if (d[:cwyear] && !year) || ((d[:cwday] || d[:cweek]) && !(d[:mon] && d[:mday])) # make_time doesn't deal with cwyear/cwday/cweek return Date.strptime(date, format).to_time end if (d[:wnum0] || d[:wnum1]) && !yday && !(d[:mon] && d[:mday]) yday = Date.strptime(date, format).yday end t = make_time(date, year, yday, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now) end t end
工作方式类似于 parse,但不是使用启发式方法检测输入字符串的格式,而是提供第二个参数来描述字符串的格式。
如果日期或格式无效,则会引发 ArgumentError。
如果给出了代码块,则 date 中描述的年份将由该代码块转换。例如:
Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
以下是格式化选项的列表:
- %a
- 
缩写的星期几名称(“Sun”) 
- %A
- 
完整的星期几名称(“Sunday”) 
- %b
- 
缩写的月份名称(“Jan”) 
- %B
- 
完整的月份名称(“January”) 
- %c
- 
首选的本地日期和时间表示形式 
- %C
- 
世纪(2009 年中的 20) 
- %d
- 
月份中的日期(01..31) 
- %D
- 
日期(%m/%d/%y) 
- %e
- 
月份中的日期,用空格填充( 1..31) 
- %F
- 
等效于 %Y-%m-%d(ISO 8601 日期格式) 
- %g
- 
商业年份的最后两位数字 
- %G
- 
根据 ISO-8601 的基于星期的年份(第一周从星期一开始,包括 1 月 4 日) 
- %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
- 
换行符(n) 
- %N
- 
小数秒位数 
- %p
- 
子午线指示符(“AM” 或 “PM”) 
- %P
- 
子午线指示符(“am” 或 “pm”) 
- %r
- 
时间,12 小时制(与 %I:%M:%S %p 相同) 
- %R
- 
时间,24 小时制(%H:%M) 
- %s
- 
自 1970-01-01 00:00:00 UTC 以来的秒数。 
- %S
- 
分钟的秒数(00..60) 
- %t
- 
制表符(t) 
- %T
- 
时间,24 小时制(%H:%M:%S) 
- %u
- 
星期几作为十进制数,星期一为 1。(1..7) 
- %U
- 
当前年份的周数,从第一个星期日作为第一周的第一天开始(00..53) 
- %v
- 
VMS 日期(%e-%b-%Y) 
- %V
- 
根据 ISO 8601 的年份周数(01..53) 
- %W
- 
当前年份的周数,从第一个星期一作为第一周的第一天开始(00..53) 
- %w
- 
星期几(星期日为 0,0..6) 
- %x
- 
首选的仅日期表示形式,不包含时间 
- %X
- 
首选的仅时间表示形式,不包含日期 
- %y
- 
不带世纪的年份(00..99) 
- %Y
- 
年份,可能包含世纪,如果提供 
- %z
- 
时区,以与 UTC 的小时偏移量表示(例如,+0900) 
- %Z
- 
时区名称 
- %%
- 
文字 “%” 字符 
- %+
- 
date(1) (%a %b %e %H:%M:%S %Z %Y) 
require 'time' Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500
您必须 require 'time' 才能使用此方法。
来源
static VALUE
time_s_mkutc(int argc, VALUE *argv, VALUE klass)
{
    struct vtm vtm;
    time_arg(argc, argv, &vtm);
    return time_gmtime(time_new_timew(klass, timegmw(&vtm)));
}
          返回一个基于给定参数的新 Time 对象,时区为 UTC。
如果给定一到七个参数,则这些参数的解释与上面的第一个调用序列相同
Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0)
示例
Time.utc(2000) # => 2000-01-01 00:00:00 UTC Time.utc(-2000) # => -2000-01-01 00:00:00 UTC
所需参数 year 没有最小值和最大值。
对于可选参数
- 
month:月份,范围为 (1..12),或不区分大小写的 3 字母月份名称Time.utc(2000, 1) # => 2000-01-01 00:00:00 UTC Time.utc(2000, 12) # => 2000-12-01 00:00:00 UTC Time.utc(2000, 'jan') # => 2000-01-01 00:00:00 UTC Time.utc(2000, 'JAN') # => 2000-01-01 00:00:00 UTC 
- 
mday:月份中的天数,范围为 (1..31)Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC Time.utc(2000, 1, 31) # => 2000-01-31 00:00:00 UTC 
- 
hour:小时,范围为 (0..23),如果min、sec和usec为零,则为 24Time.utc(2000, 1, 1, 0) # => 2000-01-01 00:00:00 UTC Time.utc(2000, 1, 1, 23) # => 2000-01-01 23:00:00 UTC Time.utc(2000, 1, 1, 24) # => 2000-01-02 00:00:00 UTC 
- 
min:分钟,范围为 (0..59)Time.utc(2000, 1, 1, 0, 0) # => 2000-01-01 00:00:00 UTC Time.utc(2000, 1, 1, 0, 59) # => 2000-01-01 00:59:00 UTC 
- 
sec:秒,范围为(0..59),如果usec为零,则为 60Time.utc(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 UTC Time.utc(2000, 1, 1, 0, 0, 59) # => 2000-01-01 00:00:59 UTC Time.utc(2000, 1, 1, 0, 0, 60) # => 2000-01-01 00:01:00 UTC 
- 
usec:微秒,范围为(0..999999)Time.utc(2000, 1, 1, 0, 0, 0, 0) # => 2000-01-01 00:00:00 UTC Time.utc(2000, 1, 1, 0, 0, 0, 999999) # => 2000-01-01 00:00:00.999999 UTC 
这些值可以是:
- 
如上所述的整数。 
- 
可转换为整数的数字 Time.utc(Float(0.0), Rational(1, 1), 1.0, 0.0, 0.0, 0.0, 0.0) # => 0000-01-01 00:00:00 UTC 
- 
String整数a = %w[0 1 1 0 0 0 0 0] # => ["0", "1", "1", "0", "0", "0", "0", "0"] Time.utc(*a) # => 0000-01-01 00:00:00 UTC 
如果给定正好十个参数,则这些参数的解释与上面的第二个调用序列相同
Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy)
其中 dummy 参数将被忽略
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Time.utc(*a) # => 0005-04-03 02:01:00 UTC
此形式对于从 Time.to_a 返回的 10 元素数组创建 Time 对象非常有用
t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006 a = t.to_a # => [5, 4, 3, 2, 1, 2000, 0, 2, false, nil] Time.utc(*a) # => 2000-01-02 03:04:05 UTC
这两种形式的前六个参数是相同的,尽管顺序不同;这些公共参数的范围对于两种形式都是相同的;请参见上文。
如果参数的数量为 8、9 或大于 10,则会引发异常。
相关: Time.local。
来源
# File lib/time.rb, line 623 def xmlschema(time) if /\A\s* (-?\d+)-(\d\d)-(\d\d) T (\d\d):(\d\d):(\d\d) (\.\d+)? (Z|[+-]\d\d(?::?\d\d)?)? \s*\z/ix =~ time 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 xmlschema format: #{time.inspect}") end end
将 time 解析为 XML Schema 定义的 dateTime,并将其转换为 Time 对象。该格式是 ISO 8601 定义的格式的受限版本。
如果 time 不符合该格式,或者 Time 类无法表示指定的时间,则会引发 ArgumentError。
有关此格式的更多信息,请参见 xmlschema。
require 'time' Time.xmlschema("2011-10-05T22:26:12-04:00") #=> 2011-10-05 22:26:12-04:00
您必须 require 'time' 才能使用此方法。
来源
# File lib/time.rb, line 83 def zone_offset(zone, year=self.now.year) off = nil zone = zone.upcase if /\A([+-])(\d\d)(:?)(\d\d)(?:\3(\d\d))?\z/ =~ zone off = ($1 == '-' ? -1 : 1) * (($2.to_i * 60 + $4.to_i) * 60 + $5.to_i) elsif zone.match?(/\A[+-]\d\d\z/) 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
返回指定时区与 UTC 之间的秒数差。
包含分钟的 Numeric 时区,例如 -10:00 或 +1330 将起作用,以及更简单的仅限小时的时区,例如 -10 或 +13。
还支持 ZoneOffset 中列出的文本时区。
如果时区与上述任何一个都不匹配,则 zone_offset 将检查本地时区(包括可能生效的夏令时更改)是否与 zone 匹配。指定 year 的值将更改用于查找本地时区的年份。
如果 zone_offset 无法确定偏移量,则将返回 nil。
require 'time' Time.zone_offset("EST") #=> -18000
您必须 require 'time' 才能使用此方法。
公共实例方法
来源
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, time1, time2, 1);
}
          返回一个新的 Time 对象,其值为 self 的数值与给定的 numeric 的和
t = Time.new(2000) # => 2000-01-01 00:00:00 -0600 t + (60 * 60 * 24) # => 2000-01-02 00:00:00 -0600 t + 0.5 # => 2000-01-01 00:00:00.5 -0600
相关: Time#-。
来源
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, time1, time2, -1);
}
          当给定 numeric 时,返回一个新的 Time 对象,其值是 self 的数值与 numeric 的差
t = Time.new(2000) # => 2000-01-01 00:00:00 -0600 t - (60 * 60 * 24) # => 1999-12-31 00:00:00 -0600 t - 0.5 # => 1999-12-31 23:59:59.5 -0600
当给定 other_time 时,返回一个 Float,其值是以秒为单位的 self 和 other_time 的数值差
t - t # => 0.0
相关: Time#+。
来源
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);
}
          将 self 与 other_time 进行比较;返回
- 
-1,如果self小于other_time。
- 
0,如果self等于other_time。
- 
1,如果self大于other_time。
- 
nil,如果self和other_time不可比较。
示例
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
来源
# File ext/json/lib/json/add/time.rb, line 32 def as_json(*) { JSON.create_id => self.class.name, 's' => tv_sec, 'n' => tv_nsec, } end
方法 Time#as_json 和 Time.json_create 可用于序列化和反序列化 Time 对象;请参阅 Marshal。
方法 Time#as_json 序列化 self,返回一个表示 self 的 2 元素哈希。
require 'json/add/time' x = Time.now.as_json # => {"json_class"=>"Time", "s"=>1700931656, "n"=>472846644}
方法 JSON.create 反序列化此类哈希,返回一个 Time 对象。
Time.json_create(x) # => 2023-11-25 11:00:56.472846644 -0600
来源
static VALUE
time_ceil(int argc, VALUE *argv, VALUE time)
{
    VALUE ndigits, v, den;
    struct time_object *tobj;
    if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
        den = INT2FIX(1);
    else
        den = ndigits_denominator(ndigits);
    GetTimeval(time, tobj);
    v = w2v(rb_time_unmagnify(tobj->timew));
    v = modv(v, den);
    if (!rb_equal(v, INT2FIX(0))) {
        v = subv(den, v);
    }
    return time_add(tobj, time, v, 1);
}
          返回一个新的 Time 对象,其数值大于或等于 self,并且其秒数被截断到精度 ndigits。
t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r) t # => 2010-03-30 05:43:25.123456789 UTC t.ceil # => 2010-03-30 05:43:26 UTC t.ceil(2) # => 2010-03-30 05:43:25.13 UTC t.ceil(4) # => 2010-03-30 05:43:25.1235 UTC t.ceil(6) # => 2010-03-30 05:43:25.123457 UTC t.ceil(8) # => 2010-03-30 05:43:25.12345679 UTC t.ceil(10) # => 2010-03-30 05:43:25.123456789 UTC t = Time.utc(1999, 12, 31, 23, 59, 59) t # => 1999-12-31 23:59:59 UTC (t + 0.4).ceil # => 2000-01-01 00:00:00 UTC (t + 0.9).ceil # => 2000-01-01 00:00:00 UTC (t + 1.4).ceil # => 2000-01-01 00:00:01 UTC (t + 1.9).ceil # => 2000-01-01 00:00:01 UTC
相关:Time#floor, Time#round。
来源
static VALUE
time_asctime(VALUE time)
{
    return strftimev("%a %b %e %T %Y", time, rb_usascii_encoding());
}
          返回 self 的字符串表示形式,由 strftime('%a %b %e %T %Y') 或其简写版本 strftime('%c') 格式化;请参阅 日期和时间格式
t = Time.new(2000, 12, 31, 23, 59, 59, 0.5) t.ctime # => "Sun Dec 31 23:59:59 2000" t.strftime('%a %b %e %T %Y') # => "Sun Dec 31 23:59:59 2000" t.strftime('%c') # => "Sun Dec 31 23:59:59 2000"
t.inspect # => "2000-12-31 23:59:59.5 +000001" t.to_s # => "2000-12-31 23:59:59 +0000"
来源
static VALUE
time_deconstruct_keys(VALUE time, VALUE keys)
{
    struct time_object *tobj;
    VALUE h;
    long i;
    GetTimeval(time, tobj);
    MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
    if (NIL_P(keys)) {
        h = rb_hash_new_with_size(11);
        rb_hash_aset(h, sym_year, tobj->vtm.year);
        rb_hash_aset(h, sym_month, INT2FIX(tobj->vtm.mon));
        rb_hash_aset(h, sym_day, INT2FIX(tobj->vtm.mday));
        rb_hash_aset(h, sym_yday, INT2FIX(tobj->vtm.yday));
        rb_hash_aset(h, sym_wday, INT2FIX(tobj->vtm.wday));
        rb_hash_aset(h, sym_hour, INT2FIX(tobj->vtm.hour));
        rb_hash_aset(h, sym_min, INT2FIX(tobj->vtm.min));
        rb_hash_aset(h, sym_sec, INT2FIX(tobj->vtm.sec));
        rb_hash_aset(h, sym_subsec,
                     quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
        rb_hash_aset(h, sym_dst, RBOOL(tobj->vtm.isdst));
        rb_hash_aset(h, sym_zone, time_zone(time));
        return h;
    }
    if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
        rb_raise(rb_eTypeError,
                 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
                 rb_obj_class(keys));
    }
    h = rb_hash_new_with_size(RARRAY_LEN(keys));
    for (i=0; i<RARRAY_LEN(keys); i++) {
        VALUE key = RARRAY_AREF(keys, i);
        if (sym_year == key) rb_hash_aset(h, key, tobj->vtm.year);
        if (sym_month == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mon));
        if (sym_day == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mday));
        if (sym_yday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.yday));
        if (sym_wday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.wday));
        if (sym_hour == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.hour));
        if (sym_min == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.min));
        if (sym_sec == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.sec));
        if (sym_subsec == key) {
            rb_hash_aset(h, key, quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
        }
        if (sym_dst == key) rb_hash_aset(h, key, RBOOL(tobj->vtm.isdst));
        if (sym_zone == key) rb_hash_aset(h, key, time_zone(time));
    }
    return h;
}
          返回名称/值对的哈希,用于模式匹配。可能的键是::year、:month、:day、:yday、:wday、:hour、:min、:sec、:subsec、:dst、:zone。
可能用法
t = Time.utc(2022, 10, 5, 21, 25, 30) if t in wday: 3, day: ..7 # uses deconstruct_keys underneath puts "first Wednesday of the month" end #=> prints "first Wednesday of the month" case t in year: ...2022 puts "too old" in month: ..9 puts "quarter 1-3" in wday: 1..5, month: puts "working day in month #{month}" end #=> prints "working day in month 10"
请注意,通过模式进行解构也可以与类检查结合使用
if t in Time(wday: 3, day: ..7) puts "first Wednesday of the month" end
如果 self 处于夏令时,则返回 true,否则返回 false。
t = Time.local(2000, 1, 1) # => 2000-01-01 00:00:00 -0600 t.zone # => "Central Standard Time" t.dst? # => false t = Time.local(2000, 7, 1) # => 2000-07-01 00:00:00 -0500 t.zone # => "Central Daylight Time" t.dst? # => true
来源
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;
}
          如果 self 和 other_time 都是具有完全相同时间值的 Time 对象,则返回 true。
来源
static VALUE
time_floor(int argc, VALUE *argv, VALUE time)
{
    VALUE ndigits, v, den;
    struct time_object *tobj;
    if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
        den = INT2FIX(1);
    else
        den = ndigits_denominator(ndigits);
    GetTimeval(time, tobj);
    v = w2v(rb_time_unmagnify(tobj->timew));
    v = modv(v, den);
    return time_add(tobj, time, v, -1);
}
          返回一个新的 Time 对象,其数值小于或等于 self,并且其秒数被截断到精度 ndigits。
t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r) t # => 2010-03-30 05:43:25.123456789 UTC t.floor # => 2010-03-30 05:43:25 UTC t.floor(2) # => 2010-03-30 05:43:25.12 UTC t.floor(4) # => 2010-03-30 05:43:25.1234 UTC t.floor(6) # => 2010-03-30 05:43:25.123456 UTC t.floor(8) # => 2010-03-30 05:43:25.12345678 UTC t.floor(10) # => 2010-03-30 05:43:25.123456789 UTC t = Time.utc(1999, 12, 31, 23, 59, 59) t # => 1999-12-31 23:59:59 UTC (t + 0.4).floor # => 1999-12-31 23:59:59 UTC (t + 0.9).floor # => 1999-12-31 23:59:59 UTC (t + 1.4).floor # => 2000-01-01 00:00:00 UTC (t + 1.9).floor # => 2000-01-01 00:00:00 UTC
相关:Time#ceil, Time#round。
来源
static VALUE
time_friday(VALUE time)
{
    wday_p(5);
}
          如果 self 代表星期五,则返回 true,否则返回 false。
t = Time.utc(2000, 1, 7) # => 2000-01-07 00:00:00 UTC t.friday? # => true
来源
static VALUE
time_getlocaltime(int argc, VALUE *argv, VALUE time)
{
    VALUE off;
    if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
        VALUE zone = off;
        if (maybe_tzobj_p(zone)) {
            VALUE t = time_dup(time);
            if (zone_localtime(off, t)) return t;
        }
        if (NIL_P(off = utc_offset_arg(off))) {
            off = zone;
            if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
            time = time_dup(time);
            if (!zone_localtime(zone, time)) invalid_utc_offset(off);
            return time;
        }
        else if (off == UTC_ZONE) {
            return time_gmtime(time_dup(time));
        }
        validate_utc_offset(off);
        time = time_dup(time);
        time_set_utc_offset(time, off);
        return time_fixoff(time);
    }
    return time_localtime(time_dup(time));
}
          返回一个新的 Time 对象,表示转换为给定时区的 self 值;如果 zone 为 nil,则使用本地时区。
t = Time.utc(2000) # => 2000-01-01 00:00:00 UTC t.getlocal # => 1999-12-31 18:00:00 -0600 t.getlocal('+12:00') # => 2000-01-01 12:00:00 +1200
有关参数 zone 的形式,请参见 时区说明符。
返回一个新的 Time 对象,表示转换为 UTC 时区的 self 值。
local = Time.local(2000) # => 2000-01-01 00:00:00 -0600 local.utc? # => false utc = local.getutc # => 2000-01-01 06:00:00 UTC utc.utc? # => true utc == local # => true
来源
static VALUE
time_hash(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    return rb_hash(w2v(tobj->timew));
}
          返回 self 的整数哈希码。
相关:Object#hash。
来源
来源
# File lib/time.rb, line 695 def httpdate getutc.strftime('%a, %d %b %Y %T GMT') end
返回一个字符串,该字符串将时间表示为 RFC 2616 定义的 HTTP 日期的 RFC 1123 日期。
day-of-week, DD month-name CCYY hh:mm:ss GMT
请注意,结果始终为 UTC (GMT)。
require 'time' t = Time.now t.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
您必须 require 'time' 才能使用此方法。
来源
static VALUE
time_inspect(VALUE time)
{
    struct time_object *tobj;
    VALUE str, subsec;
    GetTimeval(time, tobj);
    str = strftimev("%Y-%m-%d %H:%M:%S", time, rb_usascii_encoding());
    subsec = w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE)));
    if (subsec == INT2FIX(0)) {
    }
    else if (FIXNUM_P(subsec) && FIX2LONG(subsec) < TIME_SCALE) {
        long len;
        rb_str_catf(str, ".%09ld", FIX2LONG(subsec));
        for (len=RSTRING_LEN(str); RSTRING_PTR(str)[len-1] == '0' && len > 0; len--)
            ;
        rb_str_resize(str, len);
    }
    else {
        rb_str_cat_cstr(str, " ");
        subsec = quov(subsec, INT2FIX(TIME_SCALE));
        rb_str_concat(str, rb_obj_as_string(subsec));
    }
    if (TZMODE_UTC_P(tobj)) {
        rb_str_cat_cstr(str, " UTC");
    }
    else {
        /* ?TODO: subsecond offset */
        long off = NUM2LONG(rb_funcall(tobj->vtm.utc_offset, rb_intern("round"), 0));
        char sign = (off < 0) ? (off = -off, '-') : '+';
        int sec = off % 60;
        int min = (off /= 60) % 60;
        off /= 60;
        rb_str_catf(str, " %c%.2d%.2d", sign, (int)off, min);
        if (sec) rb_str_catf(str, "%.2d", sec);
    }
    return str;
}
          返回带有亚秒的 self 的字符串表示形式
t = Time.new(2000, 12, 31, 23, 59, 59, 0.5) t.inspect # => "2000-12-31 23:59:59.5 +000001"
相关:Time#ctime, Time#to_s
t.ctime # => "Sun Dec 31 23:59:59 2000" t.to_s # => "2000-12-31 23:59:59 +0000"
将 time 解析为 XML Schema 定义的 dateTime,并将其转换为 Time 对象。该格式是 ISO 8601 定义的格式的受限版本。
如果 time 不符合该格式,或者 Time 类无法表示指定的时间,则会引发 ArgumentError。
有关此格式的更多信息,请参见 xmlschema。
require 'time' Time.xmlschema("2011-10-05T22:26:12-04:00") #=> 2011-10-05 22:26:12-04:00
您必须 require 'time' 才能使用此方法。
来源
static VALUE
time_localtime_m(int argc, VALUE *argv, VALUE time)
{
    VALUE off;
    if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
        return time_zonelocal(time, off);
    }
    return time_localtime(time);
}
          如果没有给出参数
- 
如果 self是本地时间,则返回self。
- 
否则,返回用户本地时区中的一个新的 Time。t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC t.localtime # => 2000-01-01 14:15:01 -0600 
如果给出参数 zone,则返回通过将 self 转换为给定时区创建的新 Time 对象。
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC t.localtime("-09:00") # => 2000-01-01 11:15:01 -0900
有关参数 zone 的形式,请参见 时区说明符。
来源
来源
static VALUE
time_mon(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.mon);
}
          返回 self 的一年中的整数月份,范围为 (1..12)
t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006 t.mon # => 1
来源
static VALUE
time_monday(VALUE time)
{
    wday_p(1);
}
          如果 self 代表星期一,则返回 true,否则返回 false。
t = Time.utc(2000, 1, 3) # => 2000-01-03 00:00:00 UTC t.monday? # => true
返回 self 的亚秒部分中的纳秒数,范围为 (0..999_999_999);低位数字被截断,而不是四舍五入。
t = Time.now # => 2022-07-11 15:04:53.3219637 -0500 t.nsec # => 321963700
相关:Time#subsec(返回精确的亚秒)。
来源
# File lib/time.rb, line 675 def rfc2822 strftime('%a, %d %b %Y %T ') << (utc? ? '-0000' : strftime('%z')) end
返回一个字符串,该字符串将时间表示为 RFC 2822 定义的日期时间。
day-of-week, DD month-name CCYY hh:mm:ss zone
其中时区是 [+-]hhmm。
如果 self 是 UTC 时间,则使用 -0000 作为时区。
require 'time' t = Time.now t.rfc2822 # => "Wed, 05 Oct 2011 22:26:12 -0400"
您必须 require 'time' 才能使用此方法。
来源
static VALUE
time_round(int argc, VALUE *argv, VALUE time)
{
    VALUE ndigits, v, den;
    struct time_object *tobj;
    if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
        den = INT2FIX(1);
    else
        den = ndigits_denominator(ndigits);
    GetTimeval(time, tobj);
    v = w2v(rb_time_unmagnify(tobj->timew));
    v = modv(v, den);
    if (lt(v, quov(den, INT2FIX(2))))
        return time_add(tobj, time, v, -1);
    else
        return time_add(tobj, time, subv(den, v), 1);
}
          返回一个新的 Time 对象,其数值与 self 的数值相同,并且其秒值四舍五入到精度 ndigits。
t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r) t # => 2010-03-30 05:43:25.123456789 UTC t.round # => 2010-03-30 05:43:25 UTC t.round(0) # => 2010-03-30 05:43:25 UTC t.round(1) # => 2010-03-30 05:43:25.1 UTC t.round(2) # => 2010-03-30 05:43:25.12 UTC t.round(3) # => 2010-03-30 05:43:25.123 UTC t.round(4) # => 2010-03-30 05:43:25.1235 UTC t = Time.utc(1999, 12,31, 23, 59, 59) t # => 1999-12-31 23:59:59 UTC (t + 0.4).round # => 1999-12-31 23:59:59 UTC (t + 0.49).round # => 1999-12-31 23:59:59 UTC (t + 0.5).round # => 2000-01-01 00:00:00 UTC (t + 1.4).round # => 2000-01-01 00:00:00 UTC (t + 1.49).round # => 2000-01-01 00:00:00 UTC (t + 1.5).round # => 2000-01-01 00:00:01 UTC
相关:Time#ceil, Time#floor。
来源
static VALUE
time_saturday(VALUE time)
{
    wday_p(6);
}
          如果 self 代表星期六,则返回 true,否则返回 false。
t = Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC t.saturday? # => true
来源
static VALUE
time_sec(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    return INT2FIX(tobj->vtm.sec);
}
          返回 self 的分钟的整数秒,范围为 (0..60)
t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006 t.sec # => 5
注意:当存在闰秒时,秒值可能为 60。
来源
static VALUE
time_strftime(VALUE time, VALUE format)
{
    struct time_object *tobj;
    const char *fmt;
    long len;
    rb_encoding *enc;
    VALUE tmp;
    GetTimeval(time, tobj);
    MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
    StringValue(format);
    if (!rb_enc_str_asciicompat_p(format)) {
        rb_raise(rb_eArgError, "format should have ASCII compatible encoding");
    }
    tmp = rb_str_tmp_frozen_acquire(format);
    fmt = RSTRING_PTR(tmp);
    len = RSTRING_LEN(tmp);
    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, time, &tobj->vtm, tobj->timew,
                                      TZMODE_UTC_P(tobj));
        rb_str_tmp_frozen_release(format, tmp);
        if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format);
        return str;
    }
}
          返回 self 的字符串表示形式,根据给定的字符串 format 格式化。请参阅 日期和时间格式。
来源
static VALUE
time_subsec(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    return quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE));
}
          返回 self 的精确亚秒,作为 Numeric(Integer 或 Rational)
t = Time.now # => 2022-07-11 15:11:36.8490302 -0500 t.subsec # => (4245151/5000000)
如果亚秒为零,则返回整数零
t = Time.new(2000, 1, 1, 2, 3, 4) # => 2000-01-01 02:03:04 -0600 t.subsec # => 0
来源
static VALUE
time_sunday(VALUE time)
{
    wday_p(0);
}
          如果 self 代表星期日,则返回 true,否则返回 false。
t = Time.utc(2000, 1, 2) # => 2000-01-02 00:00:00 UTC t.sunday? # => true
来源
static VALUE
time_thursday(VALUE time)
{
    wday_p(4);
}
          如果 self 代表星期四,则返回 true,否则返回 false。
t = Time.utc(2000, 1, 6) # => 2000-01-06 00:00:00 UTC t.thursday? # => true
来源
static VALUE
time_to_a(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
    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),
                    RBOOL(tobj->vtm.isdst),
                    time_zone(time));
}
          返回表示 self 的 10 元素数组。
Time.utc(2000, 1, 1).to_a # => [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"] # [sec, min, hour, day, mon, year, wday, yday, dst?, zone]
返回的数组适合用作 Time.utc 或 Time.local 的参数,以创建新的 Time 对象。
来源
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;
}
          返回表示 self 的 Date 对象。
来源
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, GREGORIAN,
                                 ry, m, d,
                                 h, min, s,
                                 HAVE_CIVIL | HAVE_TIME);
    {
        get_d1(ret);
        set_sg(dat, DEFAULT_SG);
    }
    return ret;
}
          返回表示 self 的 DateTime 对象。
来源
static VALUE
time_to_f(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    return rb_Float(rb_time_unmagnify_to_float(tobj->timew));
}
          返回 self 的值,作为 Float 数字纪元秒数;包括亚秒。
self 的存储值是 Rational,这意味着返回的值可能是近似值
Time.utc(1970, 1, 1, 0, 0, 0).to_f # => 0.0 Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_f # => 0.999999 Time.utc(1950, 1, 1, 0, 0, 0).to_f # => -631152000.0 Time.utc(1990, 1, 1, 0, 0, 0).to_f # => 631152000.0
来源
static VALUE
time_to_i(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    return w2v(wdiv(tobj->timew, WINT2FIXWV(TIME_SCALE)));
}
          返回 self 的值,作为整数纪元秒数;亚秒被截断(而不是四舍五入)
Time.utc(1970, 1, 1, 0, 0, 0).to_i # => 0 Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_i # => 0 Time.utc(1950, 1, 1, 0, 0, 0).to_i # => -631152000 Time.utc(1990, 1, 1, 0, 0, 0).to_i # => 631152000
来源
# File ext/json/lib/json/add/time.rb, line 49 def to_json(*args) as_json.to_json(*args) end
返回表示 self 的 JSON 字符串
require 'json/add/time' puts Time.now.to_json
输出
{"json_class":"Time","s":1700931678,"n":980650786}
        来源
来源
static VALUE
time_to_s(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    if (TZMODE_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());
}
          返回 self 的字符串表示形式,不包含亚秒
t = Time.new(2000, 12, 31, 23, 59, 59, 0.5) t.to_s # => "2000-12-31 23:59:59 +0000"
t.ctime # => "Sun Dec 31 23:59:59 2000" t.inspect # => "2000-12-31 23:59:59.5 +000001"
来源
static VALUE
time_tuesday(VALUE time)
{
    wday_p(2);
}
          如果 self 代表星期二,则返回 true,否则返回 false。
t = Time.utc(2000, 1, 4) # => 2000-01-04 00:00:00 UTC t.tuesday? # => true
返回 self 的亚秒部分中的微秒数,范围为 (0..999_999);低位数字被截断,而不是四舍五入
t = Time.now # => 2022-07-11 14:59:47.5484697 -0500 t.usec # => 548469
相关:Time#subsec(返回精确的亚秒)。
返回 self,转换为 UTC 时区。
t = Time.new(2000) # => 2000-01-01 00:00:00 -0600 t.utc? # => false t.utc # => 2000-01-01 06:00:00 UTC t.utc? # => true
相关:Time#getutc(返回一个新的转换后的 Time 对象)。
来源
static VALUE
time_utc_p(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    return RBOOL(TZMODE_UTC_P(tobj));
}
          如果 self 表示 UTC (GMT) 中的时间,则返回 true。
now = Time.now # => 2022-08-18 10:24:13.5398485 -0500 now.utc? # => false utc = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC utc.utc? # => true
相关:Time.utc。
返回 UTC 和 self 的时区之间的偏移量(以秒为单位)。
Time.utc(2000, 1, 1).utc_offset # => 0 Time.local(2000, 1, 1).utc_offset # => -21600 # -6*3600, or minus six hours.
来源
static VALUE
time_wday(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    MAKE_TM_ENSURE(time, tobj, tobj->vtm.wday != VTM_WDAY_INITVAL);
    return INT2FIX((int)tobj->vtm.wday);
}
          返回 self 的一周中的整数日,范围为 (0..6),星期日为零。
t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006 t.wday # => 0 t.sunday? # => true
来源
static VALUE
time_wednesday(VALUE time)
{
    wday_p(3);
}
          如果 self 代表星期三,则返回 true,否则返回 false。
t = Time.utc(2000, 1, 5) # => 2000-01-05 00:00:00 UTC t.wednesday? # => true
来源
# File lib/time.rb, line 721 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
返回一个字符串,该字符串表示由 XML Schema 定义的日期时间。
CCYY-MM-DDThh:mm:ssTZD CCYY-MM-DDThh:mm:ss.sssTZD
其中 TZD 为 Z 或 [+-]hh:mm。
如果 self 是 UTC 时间,则使用 Z 作为 TZD。否则使用 [+-]hh:mm。
fraction_digits 指定用于小数秒的位数。其默认值为 0。
require 'time' t = Time.now t.iso8601 # => "2011-10-05T22:26:12-04:00"
您必须 require 'time' 才能使用此方法。
来源
static VALUE
time_yday(VALUE time)
{
    struct time_object *tobj;
    GetTimeval(time, tobj);
    MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
    return INT2FIX(tobj->vtm.yday);
}
          返回 self 对应的年份中的第几天,范围为 (1..366)。
Time.new(2000, 1, 1).yday # => 1 Time.new(2000, 12, 31).yday # => 366
来源
来源
static VALUE
time_zone(VALUE time)
{
    struct time_object *tobj;
    VALUE zone;
    GetTimeval(time, tobj);
    MAKE_TM(time, tobj);
    if (TZMODE_UTC_P(tobj)) {
        return rb_usascii_str_new_cstr("UTC");
    }
    zone = tobj->vtm.zone;
    if (NIL_P(zone))
        return Qnil;
    if (RB_TYPE_P(zone, T_STRING))
        zone = rb_str_dup(zone);
    return zone;
}
          返回 self 对应的时区字符串名称。
Time.utc(2000, 1, 1).zone # => "UTC" Time.new(2000, 1, 1).zone # => "Central Standard Time"