美文网首页
oracle 生日计算年龄(格式:xx岁xx月xx日)的问题 [

oracle 生日计算年龄(格式:xx岁xx月xx日)的问题 [

作者: 林凯特 | 来源:发表于2017-10-10 15:52 被阅读0次

    在我一次oracle开发过程中,需要根据生日计算年龄,而且是年龄还要求精确到几岁几月几日,

    由于我们日期中有闰年,闰月,其中,2月份28天或者29天,这使得精确的年龄计算起来有点麻烦。

    那么,如何通过生日精确计算年龄呢?

    语法如下:


    Select sysdate 当前日期,

                 birthday 出生日期,

                 trunc(months_between(sysdate, birthday) / 12) 年,

                 trunc(Mod(months_between(sysdate, birthday), 12)) 月,

                 trunc(sysdate -

                 add_months(birthday,

                     trunc(months_between(sysdate, birthday) / 12) * 12 +

                              trunc(Mod(months_between(sysdate, birthday), 12)))) 日, 

    From dual;


    测试示例如下:(可以自己拷贝到PL/SQL执行)


    Select to_date('2017-09-20','yyyy-mm-dd') 当前日期,

    to_date('2017-07-21','yyyy-mm-dd') 出生日期,

    trunc(months_between(to_date('2017-09-20','yyyy-mm-dd'), to_date('2017-07-21','yyyy-mm-dd')) / 12) 年,

    trunc(Mod(months_between(to_date('2017-09-20','yyyy-mm-dd'), to_date('2017-07-21','yyyy-mm-dd')), 12)) 月,

    trunc(to_date('2017-09-20','yyyy-mm-dd') -

    add_months(to_date('2017-07-21','yyyy-mm-dd'),

    trunc(months_between(to_date('2017-09-20','yyyy-mm-dd'), to_date('2017-07-21','yyyy-mm-dd')) / 12) * 12 +

    trunc(Mod(months_between(to_date('2017-09-20','yyyy-mm-dd'), to_date('2017-07-21','yyyy-mm-dd')), 12)))) 日,

    From dual;


    以上是根据生日精确计算年龄的方法,分享给大家。

    相关文章

      网友评论

          本文标题:oracle 生日计算年龄(格式:xx岁xx月xx日)的问题 [

          本文链接:https://www.haomeiwen.com/subject/rpovyxtx.html