2010-02-21 49 views
10

我有一個時間實例curr_time,其值爲Time.now,另一個字符串target_date的值爲「2010年4月17日」。如何將變量curr_time中的日期部分更改爲target_date的值?Ruby - 更改時間實例的日期部分

 
>> 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 

如何實現這一目標?

+0

如果on Rails的使用Ruby然而,有一個單獨的'Time'類與'.change()':http://api.rubyonrails.org/classes/Time.html#method-i-改變 – 2013-06-28 01:55:35

回答

10

時間對象是不可變的,所以您必須創建一個具有所需值的新時間對象。像這樣:

require 'time' 
target = Time.parse(target_date) 
curr_time = Time.mktime(target.year, target.month, target.day, curr_time.hour, curr_time.min) 
3

試試這個:

Time.parse(target_date) + curr_time.sec + curr_time.min * 60 + curr_time.hour * 60 * 60 
=> Sat Apr 17 19:30:34 +0200 2010 

你會得到從target_date日期和curr_time時間的日期時間。

+0

剛剛編輯我的答案(我第一次沒有讓你正確...)。 – road242 2010-02-21 18:43:24

+0

您也可以將其聲明爲:Time.parse(Time.now.to_date.to_s)+ time.sec.seconds + time.min.minutes + time.hour.hours – tomascharad 2016-10-25 12:57:15

16

如果使用的ActiveSupport(例如,在環境rails,或者通過

require 'active_support' 
require 'active_support/core_ext/date_time' 

改變Time對象的實施例。

>> t = Time.now 
=> Thu Apr 09 21:03:25 +1000 2009 
>> t.change(:year => 2012) 
Thu Apr 09 21:03:25 +1000 2012 
+4

僅適用於Rails:http:// api。 rubyonrails.org/classes/Time.html#method-i-change,雖然非常有用 – 2013-06-28 01:56:30