views:

38

answers:

2

I have a Time instance curr_time with the value of Time.now and another String target_date with the value, say, "Apr 17, 2010". How do I get the date part in the variable curr_time change to the value of target_date ?

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

I want curr_time to change like this:

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

How to achieve this?

+2  A: 

Try this one:

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

You will get the DateTime with the Date from target_date and the Time from curr_time.

hkda150
Just edited my answer (I did not get you right the first time...).
hkda150
Thanks! works fine.
Vijay Dev
+3  A: 

Time objects are immutable, so you have to create a new Time object with the desired values. Like this:

require 'time'
target = Time.parse(target_date)
curr_time = Time.mktime(target.year, target.month, target.day, curr_time.hour, curr_time.min)
sepp2k
Thanks for the answer! Worked great!
Vijay Dev