Convert TimeStamp in TZ string format to TimeStamp

2019-02-21 04:26发布

问题:

I have timestamp in string format i.e. "2015-03-24T07:08:24.000Z", how can I convert it back to the timestamp i.e. 2015-03-24T07:08:24.000Z from the given string in ORACLE?

回答1:

Presumably the fixed T and Z are confusing you a bit, as they aren't normal datetime format model elements. But the documentation says:

You can include these characters in a date format model:

  • Punctuation such as hyphens, slashes, commas, periods, and colons
  • Character literals, enclosed in double quotation marks

So you enclose the T and Z in double-quotes, as "T" and "Z", in your format model.

If you aren't interersted in the timezone you can use the to_timestamp() function:

to_timestamp('2015-03-24T07:08:24.000Z', 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')

Or if you want to have with the timezone you can use the to_timestamp_tz() function, which will default to your current session timezone (as you aren't actually specifying one here, the Z isn't interpreted as Zulu/UTC):

to_timestamp_tz('2015-03-24T07:08:24.000Z', 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')

If you want it with a timezone and want to specify that it is UTC you can force that with the from_tz() function:

from_tz(to_timestamp('2015-03-24T07:08:24.000Z', 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"')), 'UTC')

To see the difference those produce, specifying a timezone for the session as a demo:

alter session set time_zone = 'America/New_York';

select to_timestamp('2015-03-24T07:08:24.000Z', 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"') as no_tz,
  to_timestamp_tz('2015-03-24T07:08:24.000Z', 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"') as default_tz,
  from_tz(to_timestamp('2015-03-24T07:08:24.000Z', 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"'), 'UTC') as utc_tz
from dual;

NO_TZ
--------------------------------------------------
DEFAULT_TZ
--------------------------------------------------
UTC_TZ
--------------------------------------------------
24-MAR-15 07.08.24.000000000                       
24-MAR-15 07.08.24.000000000 AMERICA/NEW_YORK      
24-MAR-15 07.08.24.000000000 UTC                  

I'm assuming the Z is fixed and the values you get are therefore always represent UTC; if you actually get different timezones in the values you need to convert then you'll need to extract and apply those - which is doable, but difficult, and not worth going into unless you actually have that situation.