Groovy: Get duration in years

為{幸葍}努か 提交于 2019-12-01 18:15:13

How would you get it in months?

Each month has a different number of days, so what would you do?

You can get back the date this represents from now by doing:

println duration.from.now

Or, you can get the date that represents in the past by doing:

println duration.ago

And I guess you could work it out from there, but there is no in-built functionality for normalising a TimeDuration based on a given date


Edit

This sort of thing rolls from one date in the past to the specified date. I haven't done any real testing on it though, so you should take care and test the life out of it before using it in anything important...

import static java.util.Calendar.*
import groovy.time.DatumDependentDuration
import groovy.time.TimeCategory

DatumDependentDuration getAge( Date dob, Date now = new Date() ) {
  dob.clearTime()
  now.clearTime()
  assert dob < now
  Calendar.instance.with { c ->
    c.time = dob
    def (years, months, days) = [ 0, 0, 0 ]

    while( ( c[ YEAR ] < now[ YEAR ] - 1 ) || 
           ( c[ YEAR ] < now[ YEAR ] && c[ MONTH ] <= now[ MONTH ] ) ) {
      c.add( YEAR, 1 )
      years++
    }

    while( ( c[ YEAR ] < now[ YEAR ] ) ||
           ( c[ MONTH ] < now[ MONTH ] && c[ DAY_OF_MONTH ] <= now[ DAY_OF_MONTH ] ) ) {
      // Catch when we are wrapping the DEC/JAN border and would end up beyond now
      if( c[ YEAR ] == now[ YEAR ] - 1 &&
          now[ MONTH ] == JANUARY && c[ MONTH ] == DECEMBER &&
          c[ DAY_OF_MONTH ] > now[ DAY_OF_MONTH ] ) {
        break
      }
      c.add( MONTH, 1 )
      months++
    }

    while( c[ DAY_OF_YEAR ] != now[ DAY_OF_YEAR ] ) {
      c.add( DAY_OF_YEAR, 1 )
      days++
    }

    new DatumDependentDuration( years, months, days, 0, 0, 0, 0 )
  }
}

println getAge( Date.parse( 'dd/MM/yyyy', '11/10/2000' ) )

// Prints: '12 years, 2 months, 30 days'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!