Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Changing the date part of a Time instance

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?

like image 657
Vijay Dev Avatar asked Feb 21 '10 18:02

Vijay Dev


2 Answers

If you use activesupport (e.g. in a rails environment, or by

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

)

Example of changing Time object.

>> t = Time.now
=> Thu Apr 09 21:03:25 +1000 2009
>> t.change(:year => 2012)
Thu Apr 09 21:03:25 +1000 2012
like image 193
Rhett Barber Avatar answered Sep 30 '22 01:09

Rhett Barber


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)
like image 44
sepp2k Avatar answered Sep 30 '22 02:09

sepp2k