Rails and postgres group_by data considering time zone

Asked

Viewed 263 times

3

How do I group records by date where the field is datetime type? But that’s considering Timezone.

For example:

When the user type 12/10/2014 23:30:00, it is recorded in the bank 13/10/2014 01:30:00, because our fuzo time is currently -2:00.

My data in bank:

|Descrição | created_at           |
|Reg 1     |  10/10/2014 17:00:00 |
|Reg 2     |  11/10/2014 01:30:00 | <-- Gostaria que fosse considerado como o dia 10/10/2014
|Reg 3     |  09/10/2014 05:30:00 |

When I have the following code:

Movimento.select("date(created_at) as dia, count(*) as qtd").group("dia")
-> [Movimento({:dia => '09/10/2014', :qtd => 1 }), Movimento({:dia => '10/10/2014', :qtd => 1 }), Movimento({:dia => '11/10/2014', :qtd => 1 }) ]

Eu gostaria que o resultado fosse:
-> [Movimento({:dia => '09/10/2014', :qtd => 1 }), Movimento({:dia => '10/10/2014', :qtd => 2 })]

How I make Timezone considered in my select and group_by?

  • Is your application used in several different timezones? If not, the simplest way is to change the Timezone that Rails includes in the bank. Check out this reply from Soen.

  • Yes, I need it to be used with several different timezones as we have some customers who are in other countries.

2 answers

1


Your bank probably has the Timezone 'UTC', if you want to take the time zone dynamically as it is set on , use the following:

Movimento.select("date(created_at AT TIME ZONE 'UTC' AT TIME ZONE '#{Time.zone.tzinfo.name}') as dia, count(*) as qtd").group("dia")

1

For daylight saving time use BRST.

select(
    "date(created_at at time zone 'UTC' at time zone 'BRST') as dia, count(*) as qtd"
).group("dia")
  • Thank you for the reply, but I cannot use BRST because otherwise it will always be 2 hours, and if it is not in daylight time, I need to be reduced 3 hours.

  • @Bruno: It was half the answer, wasn’t it? Anderson put the part to Rails.

  • Yes, but as Anderson put Time.zone.tzinfo.name, instead of taking BRST will take America/Sao_paulo, and with that postgres knows when the date is daylight saving (-2 hours) and when it is normal time (-3 hours). The way you put it will always set -2 hours.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.