日期:2014-05-16  浏览次数:20484 次

ORACLE日期时间函数大全(二)

24,round[舍入到最接近的日期](day:舍入到最接近的星期日)
?? select sysdate S1,
?? round(sysdate) S2 ,
?? round(sysdate,'year') YEAR,
?? round(sysdate,'month') MONTH ,
?? round(sysdate,'day') DAY from dual

25,trunc[截断到最接近的日期,单位为天] ,返回的是日期类型
?? select sysdate S1,????????????????????
???? trunc(sysdate) S2,???????????????? //返回当前日期,无时分秒
???? trunc(sysdate,'year') YEAR,??????? //返回当前年的1月1日,无时分秒
???? trunc(sysdate,'month') MONTH ,???? //返回当前月的1日,无时分秒
???? trunc(sysdate,'day') DAY?????????? //返回当前星期的星期天,无时分秒
?? from dual

26,返回日期列表中最晚日期
?? select greatest('01-1月-04','04-1月-04','10-2月-04') from dual

27.计算时间差
???? 注:oracle时间差是以天数为单位,所以换算成年月,日
????
????? select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))/365) as spanYears from dual??????? //时间差-年
????? select ceil(moths_between(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))) as spanMonths from dual??????? //时间差-月
????? select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))) as spanDays from dual???????????? //时间差-天
????? select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))*24) as spanHours from dual???????? //时间差-时
????? select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))*24*60) as spanMinutes from dual??? //时间差-分
????? select floor(to_number(sysdate-to_date('2007-11-02 15:55:03','yyyy-mm-dd hh24:mi:ss'))*24*60*60) as spanSeconds from dual //时间差-秒

28.更新时间
???? 注:oracle时间加减是以天数为单位,设改变量为n,所以换算成年月,日
???? select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n*365,'yyyy-mm-dd hh24:mi:ss') as newTime from dual??????? //改变时间-年
???? select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),add_months(sysdate,n) as newTime from dual???????????????????????????????? //改变时间-月
???? select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n,'yyyy-mm-dd hh24:mi:ss') as newTime from dual??????????? //改变时间-日
???? select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n/24,'yyyy-mm-dd hh24:mi:ss') as newTime from dual???????? //改变时间-时
???? select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n/24/60,'yyyy-mm-dd hh24:mi:ss') as newTime from dual????? //改变时间-分
???? select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),to_char(sysdate+n/24/60/60,'yyyy-mm-dd hh24:mi:ss') as newTime from dual?? //改变时间-秒

29.查找月的第一天,最后一天
???? SELECT Trunc(Trunc(SYSDATE, 'MONTH') - 1, 'MONTH') First_Day_Last_Month,
?????? Trunc(SYSDATE, 'MONTH') - 1 / 86400 Last_Day_Last_Month,
?????? Trunc(SYSDATE, 'MONTH') First_Day_Cur_Month,
?????? LAST_DAY(Trunc(SYSDATE, 'MONTH')) + 1 - 1 / 86400 Last_Day_Cur_Month
?? FROM dual;


三. 字符函数(可用于字面字符或数据库列)

1,字符串截取
?? select substr('abcdef',1,3) from dual

2,查找子串位置
?? select instr('abcfdgfdhd','fd') from dual

3,字符串连接
?? select 'HELLO'||'hello world' from dual;

4, 1)去掉字符串中的空格
??? select ltrim(' abc') s1,
??? rtrim('zhang ') s2,
??? trim(' zhang ') s3 from dual
?? 2)去掉前导和后缀