Oracle中的 trunc 函数有两种用法: 截日期和截数字
trunc(date, format)
1. 用于截取给定的日期中, 到指定的时间单位(format)为止的最小时间
2. 返回的数据类型只能为 date.
3. 没有指定format 时, 即trunc(date) 的形式, 缺省的format为'DD', 即截取到日为止的最小时间.
4.format 的 'yyyy'为年 'mm'为月 'dd'为日 'hh'为小时 'mi'为分钟 'ss'为秒
实例1: 截取到年为止的最小时间
select to_char(TRUNC(sysdate, 'yyyy'), 'yyyy-mm-dd hh24:mi:ss') from dual;
输出:
这里我们给定的时间是sysdate, 即当前系统的时间, 指定的format为yyyy, trunc(sysdate, 'yyyy') 即截取给出的时间 (这里是当前系统时间) 到 年份 为止的最小时间. 这里为了直观, 我们把结果再 to_char 了一次. 当前的系统时间是2015-8-10 13:43:52, 截取到年份的最小时间, 自然是2015-01-01 00:00:00
实例2: 没有指定format的trunc(date)
select to_char(TRUNC(sysdate), 'yyyy-mm-dd hh24:mi:ss') from dual;
输出:
没有指定format, 默认截取到日为止的最小日期, 当前时间为 2015-08-10 13:44:21, 截取到日的最小时间自然是 2015-08-10 00:00:00.
补充:
trunc(date) 或 trunc(date, format) 后面如果加数字的话, 数字的默认单位是日, 如
select to_char(trunc(sysdate) + 1, 'yyyy-mm-dd hh24:mi:ss') from dual;
的输出为
当前日期是2015-08-10 13:44:53, trunc得到的结果+1 就是增加一天的日期. 如果想增加1小时, 只需要 + 1/24, 分钟秒钟怎么加可类比.
trunc(number, dicimal)
1. 用于截取数字到指定的位数, dicimal为从小数点开始数, 往前后的位数. 只是简单的截取, 不考虑四舍五入.
2. 正数dicimal 代表截取小数点后第dicimal 位之前的数值(包含dicimal ), 负数dicimal 代表截取小数点往前数的 dicimal位之前的数值,被截去的整数位用0补全.
4. 没有指定 dicimal 的时候, 默认截取到整数位.
实例1:截取小数点往后2位之前的数值
select trunc(123.456, 2) from dual;
输出:
实例2: 截取小数点往前2位之前的数值
select trunc(123.456, -2) from dual;
输出:
实例3: 没有指定dicimal 的 trunc(number)
select trunc(123.456) from dual;
输出:
最后附上官方文档:
TRUNC (date):
The TRUNC
(date) function returns date
with the time portion of the day truncated to the unit specified by the format model fmt
. This function is not sensitive to the NLS_CALENDAR
session parameter. It operates according to the rules of the Gregorian calendar. The value returned is always of data type DATE
, even if you specify a different datetime data type for date
. If you omit fmt
, then the default format model 'DD
' is used and the value returned is date
truncated to the day with a time of midnight. Refer to "ROUND and TRUNC Date Functions" for the permitted format models to use in fmt