我要计算2012-11-19到2012-11-30的天数,sql如下:SELECT months_between(To_Date('20121130','yyyymmdd')+1,To_Date('20121119','yyyymmdd')) FROM dual;
--结果为:.42
SELECT 12/30 FROM dual;
--结果为:.4
为什么两个结果会不同呢?months_between是通过什么公式计算的呢?

解决方案 »

  1.   

    官网解释:
    MONTHS_BETWEEN returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 is earlier than date2, then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise Oracle Database calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 and date2.
    译:
    MONTHS_BETWEEN 返回两个日期date1和date2之间的月数。如果date1比date2晚,则返回正数。如果date1比date2早,则返回负数。如果date1和date2是两个月的同一天或者两个月的最后一天,则返回整数。否则oracle数据库基于一个月31天来计算结果的小数部分并考虑date1和date2时间部分的差异。
      

  2.   

    MONTHS_BETWEEN 算的是月份,是说这两个月之间隔了多少个月,你要算天数的话,还的* 31 
    SELECT months_between(To_Date('20121130','yyyymmdd')+1,To_Date('20121119','yyyymmdd'))* 31  FROM dual正确算出结果为 13 因为你To_Date('20121130','yyyymmdd')+1 这个加过之后是12月01号。。
      

  3.   

    两个日期相减得到的是一个以天为单位的number,带小数.天:
    ROUND(TO_NUMBER(DATE1 - DATE2))
    小时:
    ROUND(TO_NUMBER(DATE1 - DATE2) * 24)
    分钟:
    ROUND(TO_NUMBER(DATE1 - DATE2) * 24 * 60)
    秒:
    ROUND(TO_NUMBER(DATE1 - DATE2) * 24 * 60 * 60)
    毫秒:
    ROUND(TO_NUMBER(DATE1 - DATE2) * 24 * 60 * 60 * 1000)