Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return current date in a different timezone in PostgreSQL

I'm working on an application which uses Eastern time with a database set to Pacific time. This has been causing some issues, but we're told that it can't be any other way, so we just have to work around it.

Anyway, one of the things I'm having trouble with is getting today's date. Since the database is in Pacific, if I ask for today's date using current_date at, say, 1AM, it'll give me yesterday's date. I've tried setting timezone and adding/subtracting intervals, but it never seems to work the way I expect it to, and I'd rather not have to do extensive testing at 1AM to get this to work.

Is there a somewhat simple way to return a DATE for today's date in a given time zone in PostgreSQL?

like image 764
DaaaahWhoosh Avatar asked Jun 24 '16 15:06

DaaaahWhoosh


People also ask

How do I get the current date and time in PostgreSQL?

You can use the Now() function in PostgreSQL to display the current date and time without any mention of milliseconds.

What is a PostgreSQL function that returns the current time?

The PostgreSQL CURRENT_TIME function returns the current time and the current time zone.

Does Postgres store dates as UTC?

PostgreSQL assumes your local time zone for any type containing only date or time. All timezone-aware dates and times are stored internally in UTC . They are converted to local time in the zone specified by the TimeZone configuration parameter before being displayed to the client.


2 Answers

select current_date at time zone 'UTC',current_date::timestamp ; or any other zone

enter image description here

update:

select (current_date at time zone 'UTC')::date,current_date::date

enter image description here

like image 164
Vao Tsun Avatar answered Sep 19 '22 17:09

Vao Tsun


SELECT date(timezone('EST', now()))

will return the current date in Eastern Standard Time regardless of database time zone

(or any other time zone, will however NOT work with offsets, for whatever reason...)

SELECT date(timezone('UTC±XX', now()::timestamp))

if you want to use offsets, this will only work with UTC offsets though...

like image 41
memeko Avatar answered Sep 19 '22 17:09

memeko