Ruby - 更改Time实例的日期部分

Vij*_*Dev 10 ruby time datetime

我有一个Time实例curr_time,其值为Time.now,另一个String target_date,其值为"2010年4月17日".如何将变量curr_time中的日期部分更改为target_date的值?

>> curr_time
=> Sun Feb 21 23:37:27 +0530 2010
>> target_date
=> "Apr 17, 2010"

我希望curr_time改变如下:

>> curr_time
=> Sat Apr 17 23:37:27 +0530 2010

怎么做到这一点?

小智 16

如果您使用activesupport(例如在rails环境中,或通过

require 'active_support'
require 'active_support/core_ext/date_time'
Run Code Online (Sandbox Code Playgroud)

)

更改Time对象的示例.

>> t = Time.now
=> Thu Apr 09 21:03:25 +1000 2009
>> t.change(:year => 2012)
Thu Apr 09 21:03:25 +1000 2012
Run Code Online (Sandbox Code Playgroud)

  • 仅适用于Rails:http://api.rubyonrails.org/classes/Time.html#method-i-change,虽然非常有用但 (4认同)

sep*_*p2k 10

时间对象是不可变的,因此您必须使用所需的值创建新的Time对象.像这样:

require 'time'
target = Time.parse(target_date)
curr_time = Time.mktime(target.year, target.month, target.day, curr_time.hour, curr_time.min)
Run Code Online (Sandbox Code Playgroud)