Oracle中与时间有关的计算
[sql]
# sysdate+/ 加小时
# sysdate+// 加分钟
# sysdate+/// 加秒钟
#
SQL> alter session set nls_date_format=yyyyMMdd hh:mi:ss;
Session altered
SQL> select sysdate sysdate+/ sysdate+// sysdate+/// from dual;
SYSDATE SYSDATE+/ SYSDATE+// SYSDATE+///
:: :: :: ::
SQL> 获取本周第一天
SQL> select trunc(sysdate day) from dual;
TRUNC(SYSDATEDAY
::
SQL> 获取本周最后一天
SQL> select trunc(sysdate day) + /// from dual;
TRUNC(SYSDATEDAY
::
SQL> 获取下周第 n 天
SQL> select trunc(next_day(sysdate )) trunc(next_day(sysdate )) from dual;
TRUNC(NEXT_DAY(SYSD TRUNC(NEXT_DAY(SYSD
:: ::
SQL>
SQL> 获取上月第一天
SQL> select trunc(add_months(sysdate ) month) from dual;
TRUNC(ADD_MONTHS(SY
::
SQL> select to_date(to_char(add_months(sysdate ) yyyyMM) yyyyMM) from dual;
TO_DATE(TO_CHAR(ADD
::
SQL> 获取本月第一天
SQL> select trunc(sysdate month) from dual;
TRUNC(SYSDATEMONT
::
SQL> select to_date(to_char(sysdate yyyyMM) yyyyMM) from dual;
TO_DATE(TO_CHAR(SYS
::
SQL> 获取本月最后一天
SQL> select trunc(last_day(sysdate)) + /// from dual;
TRUNC(LAST_DAY(SYSD
::
SQL> select add_months(trunc(sysdate month) ) /// from dual;
ADD_MONTHS(TRUNC(SY
::
SQL>
SQL> 获取本季度第一天
SQL> select trunc(sysdate Q) from dual;
TRUNC(SYSDATEQ)
::
SQL> 获取本季度最后一天
SQL> select add_months(trunc(sysdate Q) ) /// from dual;
ADD_MONTHS(TRUNC(SY
::
SQL>
SQL> 获取去年第一天(因为闰年平年天数不一样所以不能使用加减 或天 来计算年份)
SQL> select trunc(trunc(sysdate year) year) from dual;
TRUNC(TRUNC(SYSDATE
::
SQL> 获取今年第一天
SQL> select trunc(sysdate year) from dual;
TRUNC(SYSDATEYEAR
::
SQL> select to_date(to_char(sysdate yyyy)|| yyyyMMdd) from dual;
TO_DATE(TO_CHAR(SYS
::
SQL> 获取今年最后一天
SQL> select trunc(add_months(sysdate ) year) /// from dual;
TRUNC(ADD_MONTHS(SY
::
SQL> select to_date(to_char(sysdate yyyy)|| :: yyyyMMdd hh:mi:ss) from dual;
TO_DATE(TO_CHAR(SYS
::
SQL>
SQL> 计算相差的天数
SQL> select round(to_number(to_date( :: yyyyMMdd hh:mi:ss) to_date( :: yyyyMMdd hh:mi:ss))) value from dual;
VALUE
SQL> 计算相差的小时数
SQL> select round(to_number(to_date( :: yyyyMMdd hh:mi:ss) to_date( :: yyyyMMdd hh:mi:ss)) * ) value from dual;
VALUE
SQL> 计算相差的分钟数
SQL> select round(to_number(to_date( :: yyyyMMdd hh:mi:ss) to_date( :: yyyyMMdd hh:mi:ss)) * * ) value from dual;
VALUE
SQL>