Groovy: Get duration in years

后端 未结 1 1173
再見小時候
再見小時候 2021-01-19 00:07

On running the following code in groovy -

import groovy.time.*
import org.codehaus.groovy.runtime.TimeCategory
def today = new Date()
use(TimeCategory)
{
  d         


        
相关标签:
1条回答
  • 2021-01-19 00:20

    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'
    
    0 讨论(0)
提交回复
热议问题