oracle获得日期与向oracle表中插入Date字符串原理解析
工作中要用到
像
当显示
create table x(a int, b date);然后我们执行下面的查询语句:
select b from x;我们会看到如下结果(set head on):
B ------------ 01-APR-08 (语言是英语) 或 B ------------- 01-四月 -08 (语言是中文)
也就是说,每次显示 DATE 类型的数值时,Oracle 会自动调用
SELECT TO_CHAR(b, 'YYYY/MM/DD') AS b FROM x;
返回的结果是:
B ------------ 2008/04/01
d 是 Date 类型的变量,fmt 是我们指定的日期时间格式,如果不显式指定就用 Oracle 的默认值。 fmt 里常用的跟日期时间有关的占位符如下:
- MM 用数字表示的月份(例如,07)
- MON 缩写的月份名称(例如,JUL)
- MONTH 完整的月份名称(例如,JULY)
- DD 日期(例如, 24)
- DY 星期几的缩写(例如,FRI)
- YYYY 用4位表示的年份(例如, 2008)
- YY 用2位表示的年份,取年份的后两位(例如,08)
- RR 跟 YY 类似,但两位表示的年份被近似到 1950 到 2049 这个范围里的年份,例如 06 被认为是 2006,而不是 1906
- AM (或 PM) 上下午指示符
- HH 12进制表示的时间(1-12)
- HH24 24进制表示的时间(0-23)
- MI 分钟(0-59)
- SS 秒(0-59)
以上讲的是利用
跟 Oracle 显示日期时间时会隐性调用
还是以我们的 x 表为例,我们可以直接输入:
insert into x values(99, '31-may-08');
但是,在显示时不管用什么格式都不会影响我们实际储存的数据;在插入时,单纯采用 Oracle 的默认格式就不是那么符合工作需要了,我们还是需要显式调用
insert into x values(99, to_date('2008/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam'));
TO_DATE 函数的语法:
char 是表示日期和时间的字符串。fmt 的表示方法和
我们前面一直提到 Oracle 默认的日期时间格式是“DD-MON-YY”,其实,我们还可以修改这个默认格式,把它改成我们需要的格式。在 SQL*plus 里面输入下面的命令:
例如:
SQL> alter session set nls_date_format='yyyy-mm-dd'; 会话已更改。 SQL> insert into x (b) values('2004-08-26'); 已创建1行。
用 Oracle 内置的函数 SYSDATE 可以返回系统当前的日期和时间,例如:
select to_char(sysdate, 'Dy DD-Mon-YYYY HH24:MI:SS') as "Current Time" from dual;
todate()和tochar()两者参数基本一致,前者为日期变量,后者为你需要存储或者显示的日期转化格式
Two interesting things to note here:
You can use double quotes to make names case sensitive (by default, SQL is case insensitive), or to force spaces into names. Oracle will treat everything inside the double quotes literally as a single name. In this example, if "Current Time" is not quoted, it would have been interpreted as two case insensitive names CURRENT and TIME, which would actually cause a syntax error. DUAL is built-in relation in Oracle which serves as a dummy relation to put in the FROM clause when nothing else is appropriate. For example, try "select 1+2 from dual;". Another name for the built-in function SYSDATE is CURRENT_DATE. Be aware of these special names to avoid name conflicts.
Operations on DATE You can compare DATE values using the standard comparison operators such as =, !=, >, etc.
You can subtract two DATE values, and the result is a FLOAT which is the number of days between the two DATE values. In general, the result may contain a fraction because DATE also has a time component. For obvious reasons, adding, multiplying, and dividing two DATE values are not allowed.
You can add and subtract constants to and from a DATE value, and these numbers will be interpreted as numbers of days. For example, SYSDATE+1 will be tomorrow. You cannot multiply or divide DATE values.
With the help of TO_CHAR, string operations can be used on DATE values as well. For example, to_char(<date>, 'DD-MON-YY') like '%JUN%' evaluates to true if <date> is in June.