John Bachir
John Bachir

Reputation: 22731

Why can't I change the offset of a DateTime in rails?

I'm trying to change the offset of a DateTime, like so:

> n = Time.now
=> 2016-11-15 16:42:04 +0000
> n.change(year: 1980)
=> 1980-11-15 16:42:04 +0000
> n.change(offset: "-05:00")
=> 2016-11-15 16:42:04 +0000

As you can see, it's not working. What am I doing wrong?

Upvotes: 3

Views: 549

Answers (2)

Justin Wood
Justin Wood

Reputation: 10061

You are not allowed to change the offset in this manor. The only things that change is allowed to change are :year, :month, :day, :hour, :min, :sec.

You can see this in the current code at https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/time/calculations.rb#L96-L101.

I think you will want to use DateTime instead.

Upvotes: 3

eugene_trebin
eugene_trebin

Reputation: 1553

Try to use DateTime class instead of Time

> dt = DateTime.now
=> Tue, 15 Nov 2016 19:53:02 +0300
> dt.change(offset: "-05:00")
=> Tue, 15 Nov 2016 19:53:02 -0500

Upvotes: 2

Related Questions