Groovy:持续多年

Sof*_*ngi 5 groovy duration date

在groovy中运行以下代码 -

import groovy.time.*
import org.codehaus.groovy.runtime.TimeCategory
def today = new Date()
use(TimeCategory)
{
  def modifiedToday = today.plus(10.minutes)
  modifiedToday = modifiedToday.plus(10.months)
  modifiedToday = modifiedToday.plus(10.years)
  def duration = modifiedToday - today
  println duration.years
  println duration.months
  println duration.days
  println duration.minutes
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出 -

0
0
3956
10
Run Code Online (Sandbox Code Playgroud)

请建议,为什么我将年数和月数设为0,以及所有数值的天数.我如何获得数年和数月的价值?

tim*_*tes 6

几个月你会怎么做到的?

每个月都有不同的天数,那你会怎么做?

您可以通过以下方式返回此代表的日期:

println duration.from.now
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过执行以下操作来获取过去表示的日期:

println duration.ago
Run Code Online (Sandbox Code Playgroud)

我想你可以从那里开始工作,但没有内置的功能来根据给定的日期规范化TimeDuration


编辑

这种事情从过去的一个日期滚动到指定的日期.我没有做过任何真正的测试,所以你应该注意并测试它的生命,然后才能将它用于任何重要的事情......

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'
Run Code Online (Sandbox Code Playgroud)