Oracle开发实战-日期函数
文章内容会逐渐更新
1、对日期的常用操作
取得当前日期用sysdate;
如:
select sysdate from dual;
*日期+数字=日期:表示若干天之后的日期;如:
select sysdate+8,sysdate+300 from dual;
*日期-数字=日期:表示若干天之前的日期;
如:
select sysdate-5,sysdate-600 from dual;
*日期-日期=数字:如:求出每个雇员到今天为止的雇佣天数:
select ename,hiredate,sysdate-hiredate from emp;
*求出本月最后一天的日期:
select last_day(sysdate) from dual;
*求出下一个周一:
select next_day(sysdate,'星期一') from dual;
*求出四个月后找到工作的时间( 若干月之后的日期):
select add_months(sysdate,4) from dual;
*求出每个雇员到今天为止的雇佣月份(trunc表示截取):
select ename,hiredate,trunc(months_between(sysdate,hiredate)) from emp;
2、日期转化为字符串
select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') as nowTime from dual
3、获取时间的年
select to_char(sysdate,'yyyy') as nowYear from dual;
4、获取时间的月
select to_char(sysdate,'mm') as nowMonth from dual;
select to_char(sysdate,'dd') as nowDay from dual;
select to_char(sysdate,'hh24') as nowHour from dual;
select to_char(sysdate,'mi') as nowMinute from dual;
8、获取时间的秒
select to_char(sysdate,'ss') as nowSecond from dual;
9、字符串转换为日期
select to_date('2004-05-07 13:23:44','yyyy-mm-dd hh24:mi:ss') from dual;
10、求某天是星期几
select to_char(to_date('2016-05-22','yyyy-mm-dd'),'day') from dual;
11、求两个日期的相差天数
select floor(sysdate - to_date('20160405','yyyymmdd')) from dual;
12、转换函数
to_char(字符串|列,格式字符串):将日期或数字变为字符串显示;
to_char(字符串|列,格式字符串):将日期或数字变为字符串显示;
如:
select to_char(sysdate,'yyyy-mm-dd') from dual;
或者:
<span style="font-size:18px;">select to_char(sysdate,'yyyy')year,to_char(sysdate,'mm')months,to_char(sysdate,'dd')day from dual; </span>
如果要消除前导0的话,可以加入一个"fm";
如:
select to_char(sysdate,'fmyyyy-mm-dd') from dual;
to_date(字符串,格式字符串):将字符串变为date数据显示;
如:
select to_date('1990-08-07','yyyy-mm-dd') from dual;
to_number(字符串):将字符串变为数字显示;