我希望能够在Oracle数字字段中以毫秒为单位存储当前时间.我如何通过查询执行此操作?
select systimestamp from dual;
Run Code Online (Sandbox Code Playgroud)
返回实际的时间戳.无论如何,我可以像Java System.currentTimeMillis()
那样将其转换为毫秒级吗?
APC*_*APC 10
Java函数返回自固定时刻以来经过的毫秒数.那个时间是1970年世界贸易组织的第一天午夜,即Unix时钟时间的开始.
以下函数对PL/SQL执行相同操作.它从起始点(ms = 1)减去当前时间戳.它提取各种时间组件并将其转换为秒.最后,它将所有内容乘以1000以获得以毫秒为单位的值:
create or replace function current_millisecs
return number
is
base_point constant timestamp := to_timestamp('01-JAN-1970 00:00:00.000');
now constant timestamp := systimestamp AT TIME ZONE 'UTC' ;
begin
return (
((extract(day from (now-base_point)))*86400)
+ ((extract(hour from (now-base_point)))*3600)
+ ((extract(minute from (now-base_point)))*60)
+ ((extract(second from (now-base_point))))
) * 1000;
end;
/
Run Code Online (Sandbox Code Playgroud)
如果在数据库中启用了Java,则可能会发现创建Java存储过程更简单:
create or replace function currentTimeMillis return number as
language java name 'java.lang.System.currentTimeMillis() return java.lang.Integer';
/
Run Code Online (Sandbox Code Playgroud)
比较两种方法:
SQL> select currentTimeMillis as JAVA
2 , current_millisecs as PLSQL
3 , currentTimeMillis - current_millisecs as DIFF
4 from dual
5 /
JAVA PLSQL DIFF
---------- ---------- ----------
1.2738E+12 1.2738E+12 0
SQL>
Run Code Online (Sandbox Code Playgroud)
(我要感谢Simon Nickerson,他在我之前的PL/SQL函数版本中发现了拼写错误,产生了异常结果.)
顺便说一句,如果您只对最近的厘秒感兴趣,那么Oracle就有一个内置功能:DBMS_UTILITY.GET_TIME().
小智 5
此链接适用于所有语言 currentmillis.com for oracle:
SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000 FROM DUAL
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18924 次 |
最近记录: |