gpt4 book ai didi

Time.parse() 中的 Ruby 日期截止

转载 作者:数据小太阳 更新时间:2023-10-29 08:41:27 25 4
gpt4 key购买 nike

Ruby 的 Time.parse() 适用于从 1901 年 12 月 14 日到 2038 年 1 月 18 日的日期(这似乎取决于系统):

# works
irb(main):038:0> Time.parse('14-12-1901')
=> Sat Dec 14 00:00:00 -0600 1901

# doesn't work
irb(main):039:0> Time.parse('13-12-1901')
ArgumentError: time out of range
from /usr/lib/ruby/1.8/time.rb:184:in `local'
from /usr/lib/ruby/1.8/time.rb:184:in `make_time'
from /usr/lib/ruby/1.8/time.rb:243:in `parse'
from (irb):39
from /usr/lib/ruby/1.8/date/format.rb:214

我想不出它在那里停止工作的原因。为什么奇怪的截止?如何以编程方式获取有效范围?

最佳答案

Ruby 的 Time 类是 time_t 的包装器,它使用带符号的 int 来表示自 Unix 纪元开始以来的秒数。使用 32 位 int,这会导致您遇到 1901-2038 边界。这通常称为 Y2038 bug .

PHP 实际上也有同样的错误,所以虽然这是回答 Ruby 问题的奇怪来源,但这是 PHP 手册中的一个异常(exception):

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch.

根据 this article , Ruby 1.9.2 应该会解决这个问题(Rails 也会解决这个问题)。

或者,您可以使用 DateTime类,它能够解析您遇到问题的日期:

DateTime.parse('13-12-1901').strftime("%Y-%m-%d")
=> "1901-12-13"

关于Time.parse() 中的 Ruby 日期截止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3832524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com