我想做一个数据库支持的日历。时间目标会让我的生活更轻松吗?目前还没有..。
.end_of_year方法给了我一些奇怪的信息。
如果它是当代的话,它就会完美无缺:
date = '2012-3-2'.to_time(:utc) #=> 2012-03-02 00:00:00 UTC
date.end_of_year #=> 2012-12-31 23:59:59 UTC 然而,如果你回到过去,事情会变得奇怪。
date = '1399-3-2'.to_time(:utc) #=> 1399-03-02 00:00:00 UTC
date.end_of_year #=> 1399-12-23 23:59:59 UTC 12月23日?不是第31次吗?
它甚至不一致:
date = '0000-3-2'.to_time(:utc) #=> 0000-03-02 00:00:00 UTC
date.end_of_year #=> 0001-01-02 23:59:59 UTC嗯,1月2日?第二年的?怎么一回事?
也被对象考虑到了闰年吗?
发布于 2014-02-13 13:37:40
您可以使用DateTime代替:
date = '2012-3-2'.to_datetime #=> Fri, 02 Mar 2012 00:00:00 +0000
date.end_of_year #=> Mon, 31 Dec 2012 23:59:59 +0000
date = '1399-3-2'.to_datetime #=> Sun, 02 Mar 1399 00:00:00 +0000
date.end_of_year #=> Wed, 31 Dec 1399 23:59:59 +0000
date = '0000-3-2'.to_datetime #=> Tue, 02 Mar 0000 00:00:00 +0000
date.end_of_year #=> Fri, 31 Dec 0000 23:59:59 +0000 这是准确的莫拉,你可以格式化输出
发布于 2014-02-13 12:38:40
我做了些调查。这是我发现的。
让我们从年开始
def end_of_year
change(:month => 12).end_of_month
end它依赖于change和月份
def end_of_month
last_day = ::Time.days_in_month(month, year)
last_hour{ days_since(last_day - day) }
end最有趣的部分发生在因为内部
def days_since(days)
advance(:days => days)
end先期方法稍微复杂一点:
def advance(options)
unless options[:weeks].nil?
options[:weeks], partial_weeks = options[:weeks].divmod(1)
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
end
unless options[:days].nil?
options[:days], partial_days = options[:days].divmod(1)
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
end
d = to_date.advance(options)
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
seconds_to_advance = options.fetch(:seconds, 0) +
options.fetch(:minutes, 0) * 60 +
options.fetch(:hours, 0) * 3600
if seconds_to_advance.zero?
time_advanced_by_date
else
time_advanced_by_date.since(seconds_to_advance)
end
end,他就是我们要找的人,:
# in rails console
time = '0000-01-01'.to_time(:utc) #=> 0000-01-01 00:00:00 UTC
time.advance(days: 1) #=> 0000-01-04 00:00:00 UTC
time.advance(days: 2) #=> 0000-01-05 00:00:00 UTC
time.advance(days: 3) #=> 0000-01-06 00:00:00 UTC这就是目前的情况。我会继续挖掘。
https://stackoverflow.com/questions/21752462
复制相似问题