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;
到此这篇关于oracle日期和时间的基本命令的文章就介绍到这了,更多相关oracle日期和时间内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论