简体   繁体   中英

Convert Varchar with timezone to Timestamp in Oracle

I have a problem converting varchar to DateTime/timestamp. Here is the case

ID    EVENT_TIME(Varchar)
1    2020-04-12T09:25:53+0800
2    2020-04-12T09:25:53+0700
3    2020-04-12T09:25:53+0900

return I want, all timestamp convert to +0700

ID    EVENT_TIME(Datetime)
1    2020-04-12 10:25:53 
2    2020-04-12 09:25:53
3    2020-04-12 11:25:53

is this possible? and how can I do it using oracle?

thanks

Please use below query to convert varchar to timestamp using to_timestamp_tz and again convert it to the required time format using to_char

select ID, to_char(to_timestamp_tz(EVENT_TIME, 'YYYY-MM-DD"T"HH24:MI:SS.FF TZH:TZM'), 'YYYY-MM-DD HH24:MI:SS') as event_date from table_name;

Example:

select to_char(to_timestamp_tz('2020-04-12T09:25:53+0800', 'YYYY-MM-DD"T"HH24:MI:SS.FF TZH:TZM'), 'YYYY-MM-DD HH24:MI:SS') as event_date from dual;

在此处输入图像描述

As @Jim said, you can use to_timestamp_tz() with a character literal to convert the string to a timestamp value:

to_timestamp_tz(event_time, 'SYYYY-MM-DD"T"HH24:MI:SSTZH:TZM')

The to normalise to the +07:00 offset you can use at time zone :

to_timestamp_tz(event_time, 'SYYYY-MM-DD"T"HH24:MI:SSTZH:TZM') at time zone '+07:00'

If you don't want to keep the time zone part you can cast to a plain timestamp:

cast(
  to_timestamp_tz(event_time, 'SYYYY-MM-DD"T"HH24:MI:SSTZH:TZM') at time zone '+07:00'
  as timestamp)

Or you can cast (... as date) as you don't have fractional seconds.

Or you can convert that back to a string for display:

to_char(
  to_timestamp_tz(event_time, 'SYYYY-MM-DD"T"HH24:MI:SSTZH:TZM') at time zone '+07:00',
  'SYYYY-MM-DD HH24:MI:SS')

db<>fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM