Converting DateTime to unix time?

thnx in advance…

Time.now
=> Mon Mar 17 13:51:00 -0700 2008

Time.now.to_i
=> 1205787064

Time.at(Time.now.to_i)
=> Mon Mar 17 13:51:18 -0700 2008

but if I already have a DateTime object how do I turn that object into
unix time ?
thnx again

a = DateTime.now
a. ?? (what method ?)
=> 12345678 (unix time)

d = DateTime.now
=> #<DateTime: 106036277450423033/43200000000,-7/24,2299161>

d.to_s
=> “2008-03-17T16:01:40-07:00”

d.to_time.to_i
=> 1205794900

Time.at(d.to_time.to_i)
=> Mon Mar 17 16:01:40 -0700 2008

a = DateTime.now
a. ?? (what method ?)
=> 12345678 (unix time)

I found this:
a = DateTime.now
Time.parse(a.to_s).to_i

but I’m pretty sure theres a better way to do it…

weird: ‘udefined method to_time fo #<DateTime…’
?

Are you using rails? Or just ruby?

Everything I pasted in works for ruby 1.8.6, rails 1.2.5 via
./script/console.

before I tried with ruby (via irb).
now I tried it via the rails console I do this:

d = DateTime.now
=> #<DateTime: 106036277450423033/43200000000,-7/24,2299161>

d.to_s
=> “2008-03-17T16:01:40-07:00”

d.to_time.to_i

and now it claims - ‘undefined method ‘to_i’ for datetime…’
ruby 1.8.6
rails 2.0.2

rails 2.0.2
You’re doing something wrong… or something isn’t configured right…

$ ./script/console
Loading development environment (Rails 2.0.2)

DateTime.now.to_time.to_i
=> 1205797564

I believe u that it works for u, I mean, why wouldnt it ?
the question is why the hell will it not work for me…

the ‘to_time’ function returns a DateTime object and DateTime really
doesnt have a to_i method…
I guess the question is why to_time returns a DateTime and not a Time
object

shaish wrote:

I believe u that it works for u, I mean, why wouldnt it ?
the question is why the hell will it not work for me…

the ‘to_time’ function returns a DateTime object and DateTime really
doesnt have a to_i method…
I guess the question is why to_time returns a DateTime and not a Time
object

please enter the following:

ENV[‘RAILS_ENV’]

what do you get?

I think the problem is that you are using irb instead of
script/console…

hth

ilan

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs