0

I'm using ruby 1.8.6 on an old server.

I have a DateTime object which is created like this:

dt = DateTime.new(2021, 8, 25, 3, 30, 0).change(:offset => "+0200")
=> Wed, 25 Aug 2021 03:30:00 +0200

That's fine as is. However, I want it to be a Time object instead of a DateTime and I can't figure out how. If I call ".to_time" it just stays as a DateTime object. I can do this:

>> Time.parse(dt.to_s)
=> Wed Aug 25 02:30:00 +0100 2021

and that is showing the time in my local time zone, but I want it to be shown in the +0200 timezone, with that zone stored in the Time object.

Is this possible?

Max Williams
  • 32,435
  • 31
  • 130
  • 197
  • Calling `to_time` on a DateTime object `dt` **doesn't** return back DateTime. It returns a `Time` object - https://api.rubyonrails.org/classes/DateTime.html#method-i-to_time – kiddorails Aug 25 '21 at 10:24
  • @kiddorails that api is for rails 6.1.4. I don't know which version of Ruby it's using but presumably a very modern one. In Ruby 1.8.6 I get a DateTime object back: `dt = DateTime.new(2021, 8, 25, 3, 30, 0).change(:offset => "+0200") => Wed, 25 Aug 2021 03:30:00 +0200` `dt.class => DateTime` `dt.to_time.class => DateTime ` – Max Williams Aug 25 '21 at 10:48
  • `DateTime#change` and `DateTime#to_time` are not defined in the Ruby standard library but are added by ActiveSupport, i.e. Rails. You should check the documentation of your respective Rails version for its behavior. And you may want to try updating the app... – Holger Just Aug 25 '21 at 17:16
  • In any case, older Ruby versions could only ever represent either the local timezone or UTC in a time object. For arbitrary timezones, you would need to use either `ActiveSupport::TimeWithZone` (which was added in Rails 2.3.14) or your existing `DateTime` object. – Holger Just Aug 25 '21 at 17:22
  • Be aware the timezones (and daylight savings time) are defined by edict and as such can change at anytime with or without affective notice, and sometimes it depends on who you ask and/or what period in history you are dealing with. This is why NTP opted to just leave that part out. – Andrew Aug 25 '21 at 17:38

0 Answers0