问题
On running the following code in 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
}
I am getting the following output -
0
0
3956
10
Please suggest, why am I getting years and months as 0 and all the value in days. How do I get the value in years and months?
回答1:
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'
来源:https://stackoverflow.com/questions/14257888/groovy-get-duration-in-years