Saravanan
Saravanan

Reputation: 509

Ruby: discrepancy betwee dates when using offset method of datetime

I tried offset on the following two dates. One changed correctly and the other changed to +01:00.

"2022-05-09".in_time_zone('Singapore').change(offset: "+00:00") returns Mon, 09 May 2022 00:00:00 +01 +01:00

"2022-05-08".in_time_zone('Singapore').change(offset: "+00:00") returns Sun, 08 May 2022 00:00:00 +00 +00:00

pls, help me in understanding this.

Thanks, Saravanan

Upvotes: 0

Views: 32

Answers (1)

Stefan
Stefan

Reputation: 114178

change(offset: "+00:00") attempts to re-interpret the time values as the local time of the timezone corresponding to the given offset.

To do so, it fetches the timezone for the offset via:

time_zone = Time.find_zone(0)
#=> #<ActiveSupport::TimeZone:0x00007fd778e1dcf8 @name="Casablanca", @tzinfo=#<TZInfo::DataTimezone: Africa/Casablanca>, @utc_offset=nil>

Which gives Africa/Casablanca. And since Casablanca switched to daylight saving time in the night of May 8th 2022, you have that discrepancy:

time_zone.local(2022, 5, 8)
#=> Sun, 08 May 2022 00:00:00.000000000 +00 +00:00

time_zone.local(2022, 5, 9)
#=> Mon, 09 May 2022 00:00:00.000000000 +01 +01:00

If you want the time in UTC instead, you can use:

"2022-05-08".in_time_zone('Singapore').change(zone: 'UTC')
#=> Sun, 08 May 2022 00:00:00.000000000 UTC +00:00

"2022-05-09".in_time_zone('Singapore').change(zone: 'UTC')
#=> Mon, 09 May 2022 00:00:00.000000000 UTC +00:00

Upvotes: 3

Related Questions