2

might be a stupid question... I am a new to ruby and recently I am writing a rake task to merge multiple tables into a general one. One thing I need to do is to fetch the date from the database and then convert the date into two integers as year and month and then save them into two separate columns.

I finished this task file last week but unfortunately that file is removed by accident, so I have to write the code again. I didn't remember how I manipulated the date in the original file, I think that the way I took in the original file is way more straightforward than the current code. The current code is as follows.

fetched_time=DateTime.strptime(pr.fetched_time,"%Y-%m-%d")
dr.year =  fetched_time.strftime('%Y').to_i
dr.month = fetched_time.strftime('%m').to_i

I have tried many key words to search, but none of the results is helpful. Is the following code the best way to convert the date string to integer?

Thank you very much.

4

2 回答 2

8

Yes possible, by using Date#year:

require 'date'

d = Date.parse("20-08-2013")
d.year # => 2013
于 2013-08-22T18:48:50.580 回答
0
now = Time.now.to_s
# => "2013-09-10 11:09:14 -0500"
fetched_time=DateTime.strptime(now, "%Y-%m-%d").to_s
# => "2013-09-10T00:00:00+00:00"
year =  Date.parse(fetched_time).year
# => 2013
month = Date.parse(fetched_time).month
# => 9
year.class
# => Fixnum
month.class
# => Fixnum

或者

fetched_date=Date.strptime(now, "%Y-%m-%d").to_s
# => "2013-09-10"
date = Date.parse(fetched_date)
# => #<Date: 2013-09-10 ((2456546j,0s,0n),+0s,2299161j)>

无论如何,您不想使用 Date 对象而不是 String 吗?时间戳由什么组成?我是 Rails 和 ActiveRecord 的新手。

您将 ActiveRecord::Base.default_timezone = # 设置为什么?

如果您想知道 Date 对象中的这些额外数字是什么,请尝试将它们插入

Date.jd(2299161)
# => #<Date: 1582-10-15 ((2299161j,0s,0n),+0s,2299161j)>
Date.jd(2456546)
# => #<Date: 2013-09-10 ((2456546j,0s,0n),+0s,2299161j)>

它们是儒略日数字。最后一项是针对意大利和一些天主教国家的历法改革。

Date::ITALY
# => 2299161
于 2013-09-10T16:11:11.730 回答