检查Ruby中是否有两个时间戳是同一天

chi*_*der 23 ruby time date

我在Ruby中的Date,Datetime和Time之间有点困惑.更重要的是,我的应用程序对时区很敏感,而且我不确定如何在时区强大的情况下如何在这三者之间进行转换.

如何检查两个unix时间戳(自纪元以来的秒数)是否代表同一天?(我真的不介意它是否使用当地时间或UTC;虽然我更喜欢当地时间,只要它是一致的,我可以围绕它设计).

Anu*_*rag 40

使用标准库,将Time对象转换为Date.

require 'date'

Time.at(x).to_date === Time.at(y).to_date
Run Code Online (Sandbox Code Playgroud)

===如果两个日期对象代表同一天,则日期具有的方法为真.


KL-*_*L-7 5

ActiveSupport 为类定义了很好的to_date方法Time.这就是它的样子:

class Time
  def to_date
    ::Date.new(year, month, day)
  end
end
Run Code Online (Sandbox Code Playgroud)

使用它你可以比较这样的时间戳:

Time.at(ts1).to_date === Time.at(ts2).to_date
Run Code Online (Sandbox Code Playgroud)

如果没有扩展Time课程,这里的争议较少:

t1 = Time.at(ts1) # local time corresponding to given unix timestamp ts1
t2 = Time.at(ts2)
Date.new(t1.year, t1.month, t1.day) === Date.new(t2.year, t2.month, t2.day)
Run Code Online (Sandbox Code Playgroud)