目录
- 1. 基本类型
- 2. 常用函数
- 3. Demo
1. 基本类型
Oracle支持不同的日期格式模型,其中包括:
- ISO 8601:
YYYY-MM-DDTHH:MI:SS
,例如2024-06-20T14:30:00 - Oracle内部格式:
DD-MON-YYYY HH:MI:SS AM
,例如20-JUN-2024 02:30:00 PM
DATE
: 存储日期和时间,精确到秒
CREATE TABLE test_date (col DATE);
INSERT INTO test_date (col) VALUES (TO_DATE('2024-06-20 12:34:56', 'YYYY-MM-DD HH24:MI:SS'));
TIMESTAMP
:比DATE类型更精确,可以精确到小数秒
CREATE TABLE test_timestamp (col TIMESTAMP);
INSERT INTO test_timestamp (col) VALUES (TO_TIMESTAMP('2024-06-20 12:34:56.789', 'YYYY-MM-DD HH24:MI:SS.FF3'));
INTERVAL YEAR TO MONTH
:存储年份和月份的时间间隔
CREATE TABLE test_interval_ym (col INTERVAL YEAR TO MONTH);
INSERT INTO test_interval_ym (col) VALUES (INTERVAL '2-3' YEAR TO MONTH);
INTERVAL DAY TO SECOND
:存储天、小时、分钟、秒以及小数秒的时间间隔
CREATE TABLE test_interval_ds (col INTERVAL DAY TO SECOND);
INSERT INTO test_interval_ds (col) VALUES (INTERVAL '5 12:34:56.789' DAY TO SECOND);
2. 常用函数
-
SYSDATE:返回当前系统日期和时间。
SELECT SYSDATE FROM dual;
-
CURRENT_TIMESTAMP:返回当前系统时间戳:
SELECT CURRENT_TIMESTAMP FROM dual;
-
EXTRACT: 从日期或时间戳中提取特定的部分(如年、月、日、小时等)
SELECT EXTRACT(YEAR FROM SYSDATE) AS year FROM dual; # 2024
SELECT EXTRACT(MONTH FROM SYSDATE) AS month FROM dual; # 6
SELECT EXTRACT(DAY FROM SYSDATE) AS day FROM dual; # 20
-
TO_DATE: 将字符串转换为DATE类型:
SELECT TO_DATE('2024-06-20', 'YYYY-MM-DD') FROM dual;
-
TO_TIMESTAMP: 将字符串转换为TIMESTAMP类型:
SELECT TO_TIMESTAMP('2024-06-20 12:34:56.789', 'YYYY-MM-DD HH24:MI:SS.FF3') FROM dual;
-
TO_CHAR: 将日期或时间戳转换为字符串,可以指定格式:
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') FROM dual;
-
ADD_MONTHS: 给日期加上指定的月份数:
SELECT ADD_MONTHS(SYSDATE, 6) AS new_date FROM dual;
-
MONTHS_BETWEEN: 计算两个日期之间的月份数:
SELECT MONTHS_BETWEEN(TO_DATE('2024-12-20', 'YYYY-MM-DD'), SYSDATE) AS months_between FROM dual;
-
NEXT_DAY: 返回指定日期之后的第一个指定星期几:
SELECT NEXT_DAY(SYSDATE, 'FRIDAY') AS next_friday FROM dual;
-
LAST_DAY: 返回指定月份的最后一天:
SELECT LAST_DAY(SYSDATE) AS last_day_of_month FROM dual;
3. Demo
示例的查询有如下:
- 当前系统日期和时间
SELECT SYSDATE, CURRENT_TIMESTAMP FROM dual;
- 将字符串转换为日期并进行加减操作
SELECT TO_DATE('2024-06-20', 'YYYY-MM-DD') + 10 AS new_date FROM dual;
- 提取日期的不同部分
SELECT EXTRACT(YEAR FROM SYSDATE) AS year,
EXTRACT(MONTH FROM SYSDATE) AS month,
EXTRACT(DAY FROM SYSDATE) AS day
FROM dual;