美文网首页Joda time
Joda-Time 精确计算年龄

Joda-Time 精确计算年龄

作者: ba2cb747365a | 来源:发表于2018-11-27 07:45 被阅读55次

前言

开发中如果遇到计算年龄这种跟日历有关的场景时,相信很多人是一头雾水,然后百度。本篇介绍一下如何使用Joda-Time精确计算时间

核心对象

DateTimeFormatter

日期格式化和解析

LocalDate

日期(不带时间)

Period

周期(带时间单位。例如时,分,秒)

示例

计算1990-10-10出生的人的年龄

image.png
  • 通过PeriodType.yearMonthDay()可以计算出年龄,月份,和天数,够精确了。。可以看到计算出了28岁一个月多17天。
  • 源代码
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        LocalDate birthDay = formatter.parseDateTime("1990-10-10").toLocalDate();

        LocalDate now = new LocalDate();

        Period period = new Period(birthDay, now, PeriodType.yearMonthDay());
        String years = period.getYears() + "";
        String month = period.getMonths() + "";
        String days = period.getDays() + "";

相关文章

  • Joda-Time 精确计算年龄

    前言 开发中如果遇到计算年龄这种跟日历有关的场景时,相信很多人是一头雾水,然后百度。本篇介绍一下如何使用Joda-...

  • 使用Joda Time计算精确年龄

    之前项目中的年龄计算只是通过两个日期的年份相减,没有精确到天,导致生日的计算不精确。于是用Joda Time重新写...

  • js计算年龄(精确至秒)

    ps:注意传入生日月份时要减1

  • 用js计算年龄(精确到天)

    需求:需要实现 1岁2月3天这样的格式 方法: 此方法参考了: https://llyilo.iteye.com/...

  • 精确计算

    陈军每天晚上都喜欢去家附近的城中公园散散步。伴随着人到中年,陈军感觉到自己最近两年长胖了许多,特别是一个啤酒肚,许...

  • 串起那些临终的脸(十九)

    星星的年龄要以亿年来计算。人的年龄,刚出生时精确到分钟,很快变成小时,然后用天计算,之后不够快改成月,然后按月记也...

  • Joda-Time 日期计算

    一、前言 对于Joda-Time中Date-Time的dayOfWeek,dayOfMonth日期计算的方法,一开...

  • 时间工具包

    joda-time joda-time

  • 时间日期处理---推荐使用 Joda-Time

    categories: 日常记录tags: Java Joda-Time官网 Joda-Time使用

  • Java精确计算

    在java.math 的包中有3个class,在这我只举BigInteger的例子 BigDecimal 不可变的...

网友评论

    本文标题:Joda-Time 精确计算年龄

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