modifying the hour in a datetime object already created

J

Josselin

In my prog, I create a datetime object

d1s = DateTime.civil(2006,6,5,16,00,00)

then later on, I need to create another datetime from this one by
adding 1 day and changing the hour to 10:00:00

I can do easily

d1e = d1s + 1

but how can I modify the hour, which stays at 16:00:00 ?

thanks for your help

joss
 
J

Josselin

From: Josselin [mailto:[email protected]]
but how can I modify the hour, which stays at 16:00:00 ?

You can't - DateTime objects are immutable. You'd need to create the
DateTime object with the correct time.

It's situations like this which motivated me to make my own MutableTime
class (that internally wraps changing Time objects). I never wrapped it
up as a gem, but you can view the documentation and download it from:

http://phrogz.net/RubyLibs/rdoc/files/MutableTime_rb.html

(See the "Full Code" link on that page to download it.)

thanks a lot Gavin... that's a nice trick for me (I'll need to
manipulate dates ...)
I read 'immutable' in the class description, but did not link it to my
problem... tired.. need to break !
 
A

ara.t.howard

In my prog, I create a datetime object

d1s = DateTime.civil(2006,6,5,16,00,00)

then later on, I need to create another datetime from this one by adding 1
day and changing the hour to 10:00:00

I can do easily

d1e = d1s + 1

but how can I modify the hour, which stays at 16:00:00 ?

thanks for your help

joss

harp:~ > cat a.rb
ru
require 'date'
require 'yaml'

now = DateTime.now

year, yday = now.year, now.yday
ten_hours = Rational 10, 24

tomorrow = DateTime.ordinal year, yday + 1
ten_oclock_tomorrow = tomorrow + ten_hours

y 'now' => now
y 'ten_oclock_tomorrow' => ten_oclock_tomorrow


harp:~ > ruby a.rb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top