Ruby - Changing the date part of a Time instance

datetime, ruby, time

Solution

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)

Problem

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?

Original source