将 Ruby 日期转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4492557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Ruby Date to Integer
提问by Brig
How can I convert a Ruby Date to an integer?
如何将 Ruby 日期转换为整数?
采纳答案by Brig
Date cannot directly become an integer. Ex:
日期不能直接变成整数。前任:
$ Date.today
=> #<Date: 2017-12-29 ((2458117j,0s,0n),+0s,2299161j)>
$ Date.today.to_i
=> NoMethodError: undefined method 'to_i' for #<Date: 2017-12-29 ((2458117j,0s,0n),+0s,2299161j)>
Your options are either to turn the Date into a time then an Int which will give you the seconds since epoch:
您的选择是将日期转换为时间,然后转换为 Int,它将为您提供自纪元以来的秒数:
$ Date.today.to_time.to_i
=> 1514523600
Or come up with some other number you want like days since epoch:
或者想出一些你想要的其他数字,比如自纪元以来的天数:
$ Date.today.to_time.to_i / (60 * 60 * 24) ### Number of seconds in a day
=> 17529 ### Number of days since epoch
回答by Phrogz
t = Time.now
# => 2010-12-20 11:20:31 -0700
# Seconds since epoch
t.to_i
#=> 1292869231
require 'date'
d = Date.today
#=> #<Date: 2010-12-20 (4911101/2,0,2299161)>
epoch = Date.new(1970,1,1)
#=> #<Date: 1970-01-01 (4881175/2,0,2299161)>
d - epoch
#=> (14963/1)
# Days since epoch
(d - epoch).to_i
#=> 14963
# Seconds since epoch
d.to_time.to_i
#=> 1292828400
回答by EnabrenTane
Time.now.to_i
时间.现在.to_i
seconds since epoch format
自纪元格式以来的秒数
回答by Nowaker
Solution for Ruby 1.8 when you have an arbitrary DateTimeobject:
当您拥有任意DateTime对象时,Ruby 1.8 的解决方案:
1.8.7-p374 :001 > require 'date'
=> true
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
=> "1326585600"
回答by Wagner Braga
I had to do it recently and took some time to figure it out but that is how I came across a solution and it may give you some ideas:
我最近不得不这样做并花了一些时间来弄清楚,但这就是我遇到解决方案的方式,它可能会给您一些想法:
require 'date'
today = Date.today
year = today.year
month = today.mon
day = day.mday
year = year.to_s
month = month.to_s
day = day.to_s
if month.length <2
month = "0" + month
end
if day.length <2
day = "0" + day
end
today = year + month + day
today = today.to_i
puts today
At the date of this post, It will put 20191205.
在本文发布之日,它将放置 20191205。
In case the month or day is less than 2 digits it will add a 0 on the left.
如果月或日少于 2 位,它将在左侧添加 0。
I did like this because I had to compare the current date whit some data that came from a DB in this format and as an integer. I hope it helps you.
我这样做是因为我必须将当前日期与来自数据库的一些数据以这种格式和作为整数进行比较。我希望它能帮助你。

