SQL UTC date instead of SYSDATE - sql

Working on the following query.
SELECT MIN(departure_date), ch_invoice.invoice_id
FROM ch_invoice
INNER JOIN ch_trip
ON ch_invoice.invoice_id = ch_trip.invoice_id
WHERE departure_date < SYSDATE
AND service_rendered = 0
AND paid = 1
Group By ch_invoice.invoice_id
Since the database that it is hitting may be in a location where the date hasn't changed yet, and we are using UTC as a standard for our dates, is it possible to replace SYSDATE with something like UTCDATE? I just need to know what day UTC is currently at.

As AntDC suggested, you can use the SYS_EXTRACT_UTC() function. That converts a 'datetime with time zone' from whatever time zone it is in to UTC.
SYSDATE doesn't have a time zone. If you passed that in then it would be implicitly converted to the system time zone, so it would work, but you can use SYSTIMESTAMP instead as that is already zone-aware.
You said in a comment that you want the date, but all Oracle dates have a time component; you can get the result as a date type with the time set to midnight (which makes sense for the comparison you're doing) with TRUNC():
select systimestamp,
sys_extract_utc(systimestamp) as utctime,
trunc(sys_extract_utc(systimestamp)) as utcdate
from dual;
SYSTIMESTAMP UTCTIME UTCDATE
-------------------------------- ------------------------- -------------------
2016-04-08 17:18:27.352 +01:00 2016-04-08 16:18:27.352 2016-04-08 00:00:00
That's running on a server in the UK, so the local time is BST.
Since that doesn't involve a day change, the effect can be demonstrated using the session time instead of the server time:
alter session set time_zone = '+12:00';
select current_timestamp,
sys_extract_utc(current_timestamp) as utctime,
trunc(sys_extract_utc(current_timestamp)) as utcdate
from dual;
CURRENT_TIMESTAMP UTCTIME UTCDATE
-------------------------------- ------------------------- -------------------
2016-04-09 04:23:17.910 +12:00 2016-04-08 16:23:17.910 2016-04-08 00:00:00
My session time is 2016-04-09, but it still finds the UTC date as 2016-04-08.
(To be clear, I am not suggesting you switch to using current_timestamp or current_date; I'm using those instead of systimestamp and sysdate purely as a demo).

SELECT SYS_EXTRACT_UTC(departure_date)UTC_SYS, SYSTIMESTAMP FROM DUAL;

Related

PostgreSQL get results in current time zone

as said in the title I would like to have a query that returns the value of the time stamp in my current time zone (even according summer time!).
my_table is:
|timestamp|name|value|property1|property2|
|---|---|---|---|---|
|2021-08-01 00:00:00+00|10|0.44|0|0|
|2021-08-01 00:05:00+00|15|0.76|0|0|
|2021-08-01 00:10:00+00|12|0.28|0|0|
(Don't ask me why I cannot put this table directly in markdown...prob cause the dates)
Now for example if I have to select the 24h corresponding to the entire day in my time zone at the moment my solution is:
SELECT timestamp AT TIME ZONE 'CEST',name,value
FROM my_table
WHERE name IN (10,11,12)
AND timestamp BETWEEN '2021-08-01 00:00:00+02' AND '2021-08-02 00:00:00+02'
ORDER BY timestamp DESC
As you can see there is a problems here:
I have to specify every time if I is CEST or CET (now is CEST here)
and then I have to add +02 at the end of the dates (or +01 in CET)
There is a way to avoid this conceptual repetition?? any suggestion even to improve the query is appreciated
the command SELECT version(); gives me back PostgreSQL 12.7
Set your session's timezone appropriately.
set timezone TO 'Europe/Berlin';
select '2021-08-01 00:00:00+00'::timestamptz;
timestamptz
------------------------
2021-08-01 02:00:00+02
select '2021-12-01 00:00:00+00'::timestamptz;
timestamptz
------------------------
2021-12-01 01:00:00+01
select '2021-08-01 00:00:00'::timestamptz;
timestamptz
------------------------
2021-08-01 00:00:00+02
What is your session timezone set to now?

What is the proper way of formatting date in select query Oracle SQL

For suppose if I want sysdate,
SELECT SYSDATE as system_date FROM DUAL;
should output in the following format
14-Feb-2018 T19:50:02+00:00
i.e.,
DD-MMM-YYYY Thh:mm:ss+HH:MM
Assuming you know the date represents UTC and want the +00:00 part to be fixed:
select to_char(sysdate, 'DD-Mon-YYYY "T"HH24:MI:SS"+00:00"') from dual;
TO_CHAR(SYSDATE,'DD-MON-YYYY"T"HH24:
------------------------------------
14-Feb-2018 T20:13:08+00:00
The format model elements are in the documentation. That includes a section on character literals, which I've used for the fixed T and +00:00 parts.
As #mathguy said, this seems a bit unusual; and you might actually to leave the column as a native date and have your application or reporting tool or whatever format it for you. It depends what exactly you're doing, and whether you actually want a string value directly from the query.
As your updated question now doesn't have that pseudo-timezone, it's now even simpler, but the same idea:
select to_char(sysdate, 'DD-Mon-YYYY "T"HH24:MI:SS') from dual;
TO_CHAR(SYSDATE,'DD-MON-YYYY"T
------------------------------
14-Feb-2018 T20:17:50
If you're working with a data type that knows about time zones - i.e. not a plain DATE or TIMESTAMP - you can include those in the formatting using the appropriate model elements:
select to_char(systimestamp, 'DD-Mon-YYYY "T"HH24:MI:SSTZH:TZM') from dual;
TO_CHAR(SYSTIMESTAMP,'DD-MON-YYYY"T"
------------------------------------
14-Feb-2018 T20:24:58+00:00
which happens to still show +00:00 because my system is in the UK. With a different value it shows something appropriate:
alter session set time_zone = 'AMERICA/NEW_YORK';
select to_char(current_timestamp, 'DD-Mon-YYYY "T"HH24:MI:SSTZH:TZM') from dual;
TO_CHAR(CURRENT_TIMESTAMP,'DD-MON-YY
------------------------------------
14-Feb-2018 T15:28:57-05:00
Notice now I'm using systimestamp and current_timestamp, which are TZ-aware, and not sysdate or current_date which are not - you'l get an error if you try to get the TZH or TZM elements from those.
The format you are requesting doesn't make much sense. +00:00 is the time zone offset (otherwise what is it?) but in Oracle the DATE data type does not know about time zones. Only the Oracle data type TIMESTAMP WITH TIME ZONE should be formatted that way in Oracle.
Here is how this should be done with timestamps WITH TIME ZONE. Note that the standard SYSTIMESTAMP function is a timestamp WITH TIME ZONE. In the query below, you can see how the timestamp is formatted using my session's default, and then using an explicit format model.
SQL> select systimestamp,
2 to_char(systimestamp, 'dd-Mon-yyyy "T"hh24:mi:sstzh:tzm') as ts
3 from dual
4 ;
SYSTIMESTAMP TS
------------------------------------------- ---------------------------
14-FEB-18 12.14.18.537000 PM -08:00 14-Feb-2018 T12:14:18-08:00

Oracle sql timezone issue

My requirement here is to get time in GMT/UTC from a date type column. But when I use cast to cast date to timestamp, it is using US/Pacific timezone as reference though session timezone is set to GMT. So unless I use from_tz, I am not seeing desired result. Is there any other timezone setting in oracle sql that I need to modify to take GMT as reference always?
alter session set time_zone='+00:00';
select sessiontimezone from dual;
select current_timestamp from dual;
select sys_extract_utc(cast (sysdate as timestamp)) from dual;
select sys_extract_utc(from_tz(cast (sysdate as timestamp), '-07:00')) from dual;
select sys_extract_utc(current_timestamp) from dual;
Session altered.
SESSIONTIMEZONE
---------------------------------------------------------------------------
+00:00
CURRENT_TIMESTAMP
---------------------------------------------------------------------------
11-APR-16 08.46.42.292173 AM +00:00
SYS_EXTRACT_UTC(CAST(SYSDATEASTIMESTAMP))
---------------------------------------------------------------------------
11-APR-16 01.46.42.000000 AM
SYS_EXTRACT_UTC(FROM_TZ(CAST(SYSDATEASTIMESTAMP),'-07:00'))
---------------------------------------------------------------------------
11-APR-16 08.46.42.000000 AM
SYS_EXTRACT_UTC(CURRENT_TIMESTAMP)
---------------------------------------------------------------------------
11-APR-16 08.46.42.295310 AM
Tasks table has a date type column called task_started. I am looking to get UTC time from this date field. As part of that I was trying to alter session timezone to GMT while inserting the data so that I can simply cast it back to timestamp which is not working.
select task_started from tasks where rownum <2;
TASK_STAR
---------
10-APR-16
desc tasks;
Name Null? Type
----------------------------------------- -------- ----------------------------
...
TASK_STARTED DATE
...
This is a demo using data inserted using sysdate on a system on London time, so currently on BST (+01:00). The difference is smaller than you'd see on the west coast but the same things apply.
Mimicking your table, you can see that the session time zone has no effect on the inserted value since sysdate uses the database server time, not the session (client) time (as explained here):
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';
alter session set nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS.FF3';
alter session set nls_timestamp_tz_format = 'YYYY-MM-DD HH24:MI:SS.FF3 TZH:TZM';
create table tasks (id number, task_started date);
alter session set time_zone='America/Los_Angeles';
insert into tasks (id, task_started) values (1, sysdate);
select task_started, cast(task_started as timestamp) as ts
from tasks where rownum < 2;
TASK_STARTED TS
------------------- -----------------------
2016-04-11 11:55:59 2016-04-11 11:55:59.000
alter session set time_zone = 'UTC';
select task_started, cast(task_started as timestamp) as ts
from tasks where rownum < 2;
TASK_STARTED TS
------------------- -----------------------
2016-04-11 11:55:59 2016-04-11 11:55:59.000
So that's the BST time in both cases. There isn't any session or database setting that will show you a date (or timestamp, without a time zone) converted to a specific time zone automatically. The database doesn't know what that stored date/time represents unless you tell it. It doesn't know or case if you use sysdate, current_date, or a date literal; at the point the data is inserted into the table it has no time zone information at all.
To get the UTC equivalent you need to use from_tz to declare that the stored value represents a specific time zone; then you can use at time zone (which keeps the time zone info) or sys_extract_utc (which doesn't) on that to convert it; and optionally cast back to a date:
select from_tz(cast(task_started as timestamp), 'Europe/London') as db_tstz,
from_tz(cast(task_started as timestamp), 'Europe/London') at time zone 'UTC' as utc_tstz,
sys_extract_utc(from_tz(cast(task_started as timestamp), 'Europe/London')) as utc_ts,
cast(sys_extract_utc(from_tz(cast(task_started as timestamp), 'Europe/London')) as date) as utc_date
from tasks where rownum < 2;
DB_TSTZ UTC_TSTZ UTC_TS UTC_DATE
------------------------------ ------------------------------ ----------------------- -------------------
2016-04-11 11:55:59.000 +01:00 2016-04-11 10:55:59.000 +00:00 2016-04-11 10:55:59.000 2016-04-11 10:55:59
I've used the time zone region name so it takes care of summer time for me; you could use dbtimezone but that would always use -08:00, and as you showed in the question you need to use -07:00 at the moment. ANd you could use sessiontimezone but then you have to remember to set that properly. Obviously in your case you'd use your local region, e.g. America/Los_Angeles, instead of Europe/London.
And from that you can get the epoch, via an interval by comparing timestamps or more simply from comparing dates:
select sys_extract_utc(from_tz(cast(task_started as timestamp), 'Europe/London'))
- timestamp '1970-01-01 00:00:00' as diff_interval,
cast(sys_extract_utc(from_tz(cast(task_started as timestamp), 'Europe/London')) as date)
- date '1970-01-01' as diff_days,
86400 *
(cast(sys_extract_utc(from_tz(cast(task_started as timestamp), 'Europe/London')) as date)
- date '1970-01-01') as epoch
from tasks where rownum < 2;
DIFF_INTERVAL DIFF_DAYS EPOCH
---------------- --------- -----------
16902 10:55:59.0 16902.46 1460372159
If you put 1460372159 into an online converter (there are many) it will show the UTC time.

Get today's date - Different timezone

I just wanted to know whether the following SQL is good to convert US server time to Thailand date. As we have 12 hours difference in the time, and TH time is ahead of U.S time
SELECT TO_DATE(
TO_CHAR(
SYSTIMESTAMP AT TIME ZONE 'Asia/Bangkok', 'yyyy-mm-dd',
'NLS_DATE_LANGUAGE = american'), 'yyyy-mm-dd') AS TODAY
FROM dual;
It works perfectly fine. But are there any other better way to convert timestamp of server from one timezone to another as I need to compare today's date based on this result in my outer SQL.
You could CAST the timestamp to your desired timezone.
For example,
SQL> WITH data AS (
2 SELECT SYSTIMESTAMP AT TIME ZONE 'Asia/Bangkok' tm_bangkok FROM dual
3 )
4 SELECT tm_bangkok,
5 CAST(tm_bangkok AT TIME ZONE 'EST' AS TIMESTAMP) tm_est
6 FROM data;
TM_BANGKOK TM_EST
--------------------------------------------- ----------------------------
03-NOV-15 12.54.18.951000 PM ASIA/BANGKOK 03-NOV-15 12.54.18.951000 AM
There is no reason to cast a TIMESTAMP to CHAR and then back to TIMESTAMP again. Simply do
SELECT SYSTIMESTAMP AT TIME ZONE 'Asia/Bangkok' AS TODAY
FROM dual;

Different CURRENT_TIMESTAMP and SYSDATE in oracle

After executing this SQL in oracle 10g:
SELECT SYSDATE, CURRENT_TIMESTAMP FROM DUAL
I receive this strange output:
What is cause of the difference in time?
The server time is equal of SYSDATE value
CURRENT_DATE and CURRENT_TIMESTAMP return the current date and time in the session time zone.
SYSDATE and SYSTIMESTAMP return the system date and time - that is, of the system on which the database resides.
If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS* and CURRENT_* functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.
You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.
SYSDATE, SYSTIMESTAMP returns the Database's date and timestamp, whereas current_date, current_timestamp returns the date and timestamp of the location from where you work.
For eg. working from India, I access a database located in Paris. at 4:00PM IST:
select sysdate,systimestamp from dual;
This returns me the date and Time of Paris:
RESULT
12-MAY-14 12-MAY-14 12.30.03.283502000 PM +02:00
select current_date,current_timestamp from dual;
This returns me the date and Time of India:
RESULT
12-MAY-14 12-MAY-14 04.00.03.283520000 PM ASIA/CALCUTTA
Please note the 3:30 time difference.
SYSDATE returns the system date, of the system on which the database resides
CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of datatype TIMESTAMP WITH TIME ZONE
execute this comman
ALTER SESSION SET TIME_ZONE = '+3:0';
and it will provide you the same result.
SYSDATE provides date and time of a server.
CURRENT_DATE provides date and time of client.(i.e., your system)
CURRENT_TIMESTAMP provides data and timestamp of a clinet.
Note: SYSDATE - returns only the date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:
SELECT SYSDATE FROM DUAL;
will return output similar to the following: 12/15/2017 12:42:39 PM
SYSDATE, systimestamp return datetime of server where database is installed. SYSDATE - returns only date, i.e., "yyyy-mm-dd". systimestamp returns date with time and zone, i.e., "yyyy-mm-dd hh:mm:ss:ms timezone"
now() returns datetime at the time statement execution, i.e., "yyyy-mm-dd hh:mm:ss"
CURRENT_DATE - "yyyy-mm-dd", CURRENT_TIME - "hh:mm:ss", CURRENT_TIMESTAMP - "yyyy-mm-dd hh:mm:ss timezone". These are related to a record insertion time.